package test;
public class ThreadTest {
public static void main(String args[]){
Resource r = new Resource();
Product p = new Product(r);
Consume c = new Consume(r);
Thread tp = new Thread(p);
Thread tc = new Thread(c);
tp.start();
tc.start();
}
}
/**
* 数据源
* @author 郭胜
*
*/
class Resource{
private String name;
private int count;
boolean flag = true;//如果是真,则生产,如果是假,则消费
/**
* 生产
* @param name
*/
public synchronized void product(String name){
if(flag){
this.name = name;
++count;
System.out.println(Thread.currentThread().getName()+"生产了"+name+"……"+count);
flag = false;
notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 消费
*/
public synchronized void consume(){
if(!flag){
System.out.println(Thread.currentThread().getName()+"消费了……"+name+"……"+count);
flag = true;
notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 生产类
* @author 郭胜
*
*/
class Product implements Runnable{
private Resource resource;
public Product(Resource resource){
this.resource = resource;
}
public void run() {
while(true){
resource.product("面包");
}
}
}
class Consume implements Runnable{
private Resource resource;
public Consume(Resource resource){this.resource = resource;}
public void run() {
while(true){
resource.consume();
}
}
}
java线程之生产者消费者
最新推荐文章于 2025-07-04 00:15:00 发布