黑马程序员技术交流社区
标题:
一个小小的问题,求大神帮忙解释一下
[打印本页]
作者:
qinhaihang
时间:
2015-5-10 15:05
标题:
一个小小的问题,求大神帮忙解释一下
class Resource{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name+"..."+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag){ //当处于等待状态的线程被唤醒时,应该再进行一次标志的判断,故而将if更换为while
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+".....消费者...."+this.name);
flag = false;
this.notifyAll(); //因为在等待的线程池中,先进入线程池中的会先唤醒,所以需要用notifyAll唤醒所有的线程
}
}
class Producer implements Runnable{
private Resource res;
public Producer(Resource res) {
this.res = res;
}
public void run() {
while(true){
res.set("+商品+");
}
}
}
class Consumer implements Runnable{
private Resource res;
public Consumer(Resource res) {
this.res = res;
}
public void run() {
while(true){
res.out();
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource r = new Resource();
/*
* 当开启的线程超过两个时,这段代码会出现问题
*
*/
//new Thread(new Producer(r)).start(); //代码优化的写法
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
复制代码
在上边的代码中,类Resource里面有一个while循环,我不是很理解它是怎么结束这个循环的,求大神给指点一下
作者:
396460221
时间:
2015-5-10 18:51
结束run方法就可以结束线程。在Consumer和Producer的run方法中,可以定义标记,当标记为假是run方法就结束,或者直接给定循环次数。你写true不好结束的。
作者:
大西洋
时间:
2015-5-10 18:53
是通过 flag = false 结束循环的~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2