@frank-shaw
2015-10-29T11:05:49.000000Z
字数 1335
阅读 2730
java.多线程
package 生产者消费者;
/*
* 一开始想要做的是单生产者单消费者,没想到后来变成了多生产多消费,改一个东西就够了
*
* 经验教训:
*
* 1.notify()之前必须有另外一个线程正在wait(),否则notify()无效
* 2.资源类不一定就需要实现接口Runnable,也可以作为实现接口类的输入量
* 3.逻辑上需要能够过得去,不要写出来就依赖于调试,可以自己头脑运运
*/
public class Producer1Customer1 {
static Object lock = new Object();
public static void main(String[] args) {
Source ps = new Source();
Producer p1 = new Producer(ps);
Producer p2 = new Producer(ps);
Producer p3 = new Producer(ps);
Customer c1 = new Customer(ps);
Customer c2 = new Customer(ps);
Customer c3 = new Customer(ps);
new Thread(p1).start();
new Thread(p2).start();
new Thread(p3).start();
new Thread(c1).start();
new Thread(c2).start();
new Thread(c3).start();
}
}
//资源类
class Source{
int num=100;
boolean flag = false;
}
//生产者
class Producer implements Runnable{
Source ps;
public Producer(Source ps){
this.ps = ps;
}
@Override
public void run() {
while(true){
synchronized(ps){
if(ps.flag){
if(ps.num >0){
System.out.println(Thread.currentThread().getName()+"生产者"+ps.num);
ps.num = ps.num -1;
ps.flag = false;
ps.notifyAll();
}
else return;
}
else{
try{
ps.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
//消费者
class Customer implements Runnable{
Source ps;
public Customer(Source ps){
this.ps = ps;
}
@Override
public void run() {
while(true){
synchronized(ps){
if(!ps.flag){
if(ps.num>0){
System.out.println(Thread.currentThread().getName()+"消费者" + ps.num);
ps.flag = true;
ps.notifyAll();
}
}
else{
try{
ps.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}