黑马程序员技术交流社区
标题:
线程同步问题
[打印本页]
作者:
Zhang_qian
时间:
2012-5-21 20:05
标题:
线程同步问题
public class Exercise3 {
public static void main(String[] args) {
final Printer p=new Printer();
new Thread(){
public void run()
{
for(int i=0;i<5;i++)
p.print1();
}
}.start();
new Thread(){
public void run()
{
for(int i=0;i<5;i++)
p.print2();
}
}.start();
}
}
class Printer
{
private int turn=1;
public synchronized void print1()
{
if(turn!=1)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("A");
turn=2;
this.notify();
}
public synchronized void print2()
{
if(turn!=2)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("B");
turn=1;
this.notify();
}
}这里为什么只打印了一次A,B???不明白,请高手帮忙讲解一下,谢谢!
作者:
8161776
时间:
2012-5-21 20:31
public class Exercise3 {
public static void main(String[] args) {
final Printer p=new Printer();
new Thread(){
public void run()
{
for(int i=0;i<5;i++)
p.print1();
}
}.start();
new Thread(){
public void run()
{
for(int i=0;i<5;i++)
p.print2();
}
}.start();
}
}
class Printer
{
private int turn=1;
//第一次调用这个方法的时候turn =1,顺利执行完一次以后turn=2了然后下面
public synchronized void print1()
{
if(turn!=1)
try {
this.wait();//到这里这个线程就wait住了,你永远执行不到下面的 this.notify();
//你自己wait又让自己把自己唤醒?他已经wait怎么唤醒自己
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("A");
turn=2;
this.notify();
}
public synchronized void print2()
{
if(turn!=2)
try {
this.wait();//这里同理
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("B");
turn=1;
this.notify();
}
}这里为什么只打印了一次A,B???不明白,请高手帮忙讲解一下,谢谢!
复制代码
作者:
云惟桉
时间:
2012-5-21 20:53
class Printer
{
private int turn=1;
public synchronized void print1()
{
if(turn!=1) [color=Red]// turn == 2时执行[/color]
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
else [color=Red]// turn ==1时执行[/color]
System.out.println("A");
turn=2; [color=Red]//执行完毕,又让turn =2;[/color]
this.notify(); [color=Red]//此时又唤醒本方线程 打印 B [/color]
}
public synchronized void print2()
{
if(turn!=2)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("B");
turn=1;
this.notify();
}
}
复制代码
楼上的兄弟已经把问题指出来了。就是唤醒的部分。我的解释在注释里。
1、初始时 turn=1; 那么打印了一次 A 然后 turn =2;
2、判断 turn =2 ;那么等待。
此时执行不到下面的语句,就没有人将该线程唤醒了,因此陷入了无限等待,结果只有AB
我想楼主要实现的是互相唤醒对方线程吧,把代码好好审核一遍,改一遍,就会对错误记忆犹新,不会再犯了。
希望楼主能有所收获!
作者:
小小企鹅
时间:
2012-5-21 21:07
楼主可以把print1()和print2()写到一个方法中,就不会出现争用数据导致的并发问题
作者:
Zhang_qian
时间:
2012-5-22 10:54
云惟桉 发表于 2012-5-21 20:53
楼上的兄弟已经把问题指出来了。就是唤醒的部分。我的解释在注释里。
1、初始时 turn=1; 那么打印了一次 A ...
谢谢讲解!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2