スレッド通信(同期起動メカニズム)-生産者と消費者
1826 ワード
package com.companyname;
public class Test {
public static void main(String[] args) {
Resource res=new Resource();
Thread t1=new Thread(new Product(res));
Thread t2=new Thread(new Product(res));
Thread t3=new Thread(new Consumer(res));
Thread t4=new Thread(new Consumer(res));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource {
private int num = 0;
private boolean flag=true;
public synchronized void produce() {
while (true) {
if (flag) {
System.out.println(Thread.currentThread().getName()+" ......."+(++num));
flag=false;
}
else
{
this.notifyAll(); //
try {
this.wait(); //
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public synchronized void consume() {
while (true) {
if(!flag){
System.out.println(Thread.currentThread().getName()+" "+num);
flag=true;
}
else
{
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Product implements Runnable {
private Resource res;
public Product(Resource res) {
this.res = res;
}
public void run() {
res.produce(); //
}
}
class Consumer implements Runnable {
private Resource res;
public Consumer(Resource res) {
this.res = res;
}
public void run() {
res.consume(); //
}
}