多线程总结代码

package gay;
//一个商店有一种商品,边生产边消费,生产二十个就停止,消费二十个就生产
class dian {// 店员
  int ii;
    public synchronized void add()
    {
        if(ii>=20)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else
        {
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ii++;
            System.out.println(Thread.currentThread().getName()+"生产了第"+ii+"个产品");
            notify();
        }
        
    }
    public synchronized void xiao()
    {
        if(ii<=0)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else
        {try {
            Thread.currentThread().sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            ii--;
            System.out.println(Thread.currentThread().getName()+"生产了第"+ii+"个产品");
            notify();
        }
    }
    
}

class chang implements Runnable{// 工厂
    dian dia;

    public chang(dian dia) {
        this.dia = dia;
    }

    @Override
    public void run() {
        System.out.println("开始生产");
        while (true) {
            dia.add();
        }
        
    }
}

class xiao implements Runnable{// 消费
    dian dia;

    public xiao(dian dia) {
        this.dia = dia;
    }

    public void run() {
        System.out.println("消费生产");
        while (true) {
            dia.xiao();
        }
    }
}

public class Sded {
public static void main(String[] args) {
    dian d=new dian();
    chang c=new chang(d);
    xiao x=new xiao(d);
    Thread thread=new Thread(c);
    Thread thread2=new Thread(x);
    Thread thread3=new Thread(x);
    thread.setName("线程1");
    thread2.setName("线程2");
    thread3.setName("线程3");
    thread.start();
    thread2.start();
    thread3.start();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值