黑马程序员技术交流社区
标题:
问一下关于多线程wait()的问题
[打印本页]
作者:
梵天的梦
时间:
2014-3-2 22:31
标题:
问一下关于多线程wait()的问题
class Resourse
{
private String name;
private int count = 1;
private boolean flag;
public synchronized void set(String name){
if(flag){
//wait和notify前面默认是this,所以封装起来后不加this也可以
try{System.out.println("ABC");
wait();
System.out.println("123");
}catch(Exception e){}
}
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"---生产者---"+this.name);
flag = true;
notify();
}
public synchronized void get(){
// if(!flag)
//线程wait被唤醒之后不会返回判断,直接向下执行
// try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--消费者--"+this.name);
flag = false;
notify();
}
}
class Producer implements Runnable
{
Resourse res;
Producer(Resourse res){
this.res = res;
}
public void run(){
while(true){
res.set("+商品+");
}
}
}
class Consumer implements Runnable
{
Resourse res;
Consumer(Resourse res){
this.res = res;
}
public void run(){
while(true)
res.get();
}
}
class ProducerConsumerDemo
{
public static void main(String[] args){
Resourse r = new Resourse();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}
}
我想问一下,如果t1线程被wait()后,t2线程执行到函数get方法中的notify唤醒了t0线程,那么这个时候t0线程一定得到锁吗(t0是被wait()结束的)?
作者:
1844611785
时间:
2014-3-3 22:31
你的这里面不是总共是三个线程吗?一个是main ,一个是线程t1,一个是线程t2,哪来的线程t0,应该是t1 吧,这样的话,当t1等待,也就是释放执行权,随之释放锁,t2开始执行。当t2唤醒t1时,活着的线程是t1和t2,当线程t2遇到flag时条件满足,t2等待,t1获得锁了.
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2