package 生產者消費者;
public class ProducerConsumerTest {
public static void main(String[] args) {
PublicResource resource = new PublicResource();
new Thread(new ProducerThread(resource)).start();
new Thread(new ConsumerThread(resource)).start();
new Thread(new ProducerThread(resource)).start();
new Thread(new ConsumerThread(resource)).start();
new Thread(new ProducerThread(resource)).start();
new Thread(new ConsumerThread(resource)).start();
}
}
package 生產者消費者;
/**
* 生產者線程,負責生產公共資源
* @author dream
*
*/
public class ProducerThread implements Runnable{
private PublicResource resource;
public ProducerThread(PublicResource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.increase();
}
}
}
package 生產者消費者;
/**
* 消費者線程,負責消費公共資源
* @author dream
*
*/
public class ConsumerThread implements Runnable{
private PublicResource resource;
public ConsumerThread(PublicResource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resource.decrease();
}
}
}
package 生產者消費者;
/**
* 公共資源類
* @author dream
*
*/
public class PublicResource {
private int number = 0;
private int size = 10;
/**
* 增加公共資源
*/
public synchronized void increase()
{
while (number >= size) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
number++;
System.out.println("生產了1個,總共有" + number);
notifyAll();
}
/**
* 減少公共資源
*/
public synchronized void decrease()
{
while (number <= 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
number--;
System.out.println("消費了1個,總共有" + number);
notifyAll();
}
}