public class InputOutputDemo2 {
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
//用匿名对象简化代码,因为只调用该对象的一个方法--start方法--一次
new Thread(new Output(r)).start();
/*
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
*/
}
}
结果:
【SET】丽丽1女
【OUT】丽丽1女
【SET】丽丽2女
【OUT】丽丽2女
【SET】丽丽3女
【OUT】丽丽3女
【SET】丽丽4女
【OUT】丽丽4女
【SET】丽丽5女
【OUT】丽丽5女
对于多个生产者和消费者,为什么要定义while判断标记。
原因:让被唤醒的线程再一次判断标记。
为什么定义notifyAll:需要唤醒对方线程。只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource r = new Resource();
new Thread(new Producer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
}
}
class Resource {
private String name;
private int count = 1; //为商品编号
private boolean flag = false;
// t1 t2
public synchronized void set(String name) {
while (flag) {
//如果用if,线程判断完如停在这儿等再被唤醒就不再判断直接向下运行
try {
this.wait();
} catch (Exception e) {
} //t1(放弃资格) t2(获取资格)
}
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者.." + this.name);
flag = true;
this.notifyAll();
}
// t3 t4
public synchronized void out() {
while (!flag) {
try {
wait();
} catch (Exception e) {
} //t3(放弃资格) t4(放弃资格)
}
System.out.println(Thread.currentThread().getName() + "...消费者........." + this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable {
private Resource res;
Producer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.set("+商品+");
}
}
}
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.out();
}
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-55883-6.html
只是为利益的流氓而已
就算你唱歌好听那你也是一个没人知道的路人