(一)线程同步
实现生产者消费者问题来说明线程问题,举例如下所示:
/**
* 生产者消费者问题
*/
public class ProducerConsumer {
/**
* 主方法
*/
public static void main(String[] args) {
ProductBox pb = new ProductBox();
Producer p = new Producer(pb);
Consumer c = new Consumer(pb);
//根据消费者、生产者生成线程
Thread pThread = new Thread(p);
Thread cThread = new Thread(c);
pThread.setPriority(Thread.MAX_PRIORITY);
pThread.start();
cThread.start();
}
}
/**
* 产品对象
* @author johsnton678
*/
class Product {
int id;
public Product(int id) {
super();
this.id = id;
}
public String toString(){
return "Product:" + id;
}
}
/**
* 产品盒对象
* @author johnston678
*/
class ProductBox {
Product[] productbox = new Product[6];
int index = 0;
public ProductBox() {
super();
}
//存入方法,将产品存入产品盒
public synchronized void push(Product p) {
//判断产品是否超出产品盒的最大容量,如果超出中则等待
while (index == productbox.length) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
productbox[index] = p;
index ++;
}
//取出操作
public synchronized Product pop() {
//如果产