多线程编程

生产者消费者例子





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());
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值