生产者消费者例子
public class Thread_test {
public static void main(String[] args) {
SyncContainer container = new SyncContainer();
new Producer(container).start();
new Cumtomer(container).start();
}
}
//生产者
class Producer extends Thread{
private SyncContainer container;
public Producer(SyncContainer container ) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Product(i));
System.out.println("生产者正在生产第" + i + "个产品");
}
}
}
//消费者
class Cumtomer extends Thread{
private SyncContainer container;
public Cumtomer(SyncContainer container ) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费者正在消费第" + container.pop().id + "个产品");
}
}
}
//产品
class Product {
public int id;
public Product(int id) {
this.id = id;
}
}
//容器,缓冲区
class SyncContainer {
private Product aProducts[] = new Product[10];
private volatile int iProduceCount = 0;
public synchronized void push(Product product){
//容器满了
if(iProduceCount + 1 == aProducts.length){
//等待消费者
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
aProducts[iProduceCount] = product;
iProduceCount++;
//通知 消费者去消费
this.notifyAll();
return;
}
public synchronized Product pop(){
if (0 == iProduceCount){
try {
//等待生产者生产
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
iProduceCount--;
Product product = aProducts[iProduceCount];
//消费完了 通知生产者生产
this.notifyAll();
return product;
}
}
线程池
import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Thread_pool { public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { service.execute(new MyThreadPool()); } service.shutdown(); } } class MyThreadPool implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } }