您的位置:首页 > 编程语言 > Java开发

java实现线程同步一个生产者和一个消费者

2015-03-04 18:21 525 查看
package test;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test{
static Scanner sc = new Scanner(System.in);
static String line;

static class Food{
static int id = 0;
private int mid = id++;
public Food() {

}

@Override
public String toString() {
return "食物id="+mid;
}
}
static Food f = null;
static class Producer implements Runnable{
@Override
public void run() {
while(!Thread.interrupted()){
synchronized (this) {//等待过程,对应消费过程,所以应该上锁
while(f!=null){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("生产");
synchronized (c) {
f = new Food();
c.notifyAll();
}
}
}
}

static class Comsumer implements Runnable{
@Override
public void run() {
while(!Thread.interrupted()){
synchronized (this) {
while(f==null){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("消费"+f);
synchronized (p) {
f = null;
p.notifyAll();
}
}
}
}

static Producer p = new Producer();
static Comsumer c = new Comsumer();
public static void main(String[] args) {
ExecutorService exe = Executors.newCachedThreadPool();
exe.execute(p);
exe.execute(c);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: