黑马程序员技术交流社区
标题:
Java线程问题
[打印本页]
作者:
zhkqy
时间:
2013-12-6 18:36
标题:
Java线程问题
本帖最后由 zhkqy 于 2013-12-9 18:30 编辑
有A、B、C三个类(三条线程),让A先执行一秒,然后执行B、C, B、C执行完后,再执行A。我调用wait方法后,不知道在哪里调用notifyAll方法
作者:
kongling
时间:
2013-12-7 23:23
实现代码参考:
package biji;
public class Test4
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
final ThreadTest test=new ThreadTest();
new Thread(new Runnable()
{
@Override
public void run()
{
while(true)
{
test.A();
// TODO Auto-generated method stub
}
}
}).start();;
new Thread(new Runnable()
{
@Override
public void run()
{
while(true)
{
test.B();
// TODO Auto-generated method stub
}
}
}).start();;
new Thread(new Runnable()
{
@Override
public void run()
{
while(true)
{
test.C();
// TODO Auto-generated method stub
}
}
}).start();;
}
}
class ThreadTest
{
boolean tagB=true;
boolean tagC=true;
public synchronized void A()
{
while((tagB && tagC)==false)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
System.out.println("A finish");
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
tagB=false;
tagC=false;
this.notifyAll();
}
public synchronized void B()
{
while(tagB==true)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("B finish");
tagB=true;
this.notifyAll();
}
public synchronized void C()
{
while(tagC==true)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("C finish");
tagC=true;
this.notifyAll();
}
}
复制代码
作者:
Weix1992
时间:
2013-12-7 23:42
我提供一种思路,不保证一定可行,我没有试验。
用1.5的新特性, Condition a = lock.newCondition();
Condition b = lock.newCondition();
Condition c = lock.newCondition();
用3个Condition 分别对应三个线程, B,C线程启动的时候都是await()的,然后a控制b,b控制c,c控制a每个线程用lock锁上
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2