第09章_线程_生产者与消费者及 第九章线程总结

关键字  wait();    notify()

// 创建 tong   mantou   chushi  xiaofeizhe   四个类。

mantou具有ID

tong 具有容量  mantou[]数组,及 index  馒头的数量

chushi生产mantou

xiaofeizhe 消费mantou



public class Test20180601{

public static void main(String args[]){
tong t1 = new tong();
chushi c1 = new chushi(t1);
xiaofeizhe x1 = new xiaofeizhe(t1);
new Thread(c1).start();
new Thread(x1).start();
}
}


class mantou {
int ID=0;


mantou(int i){
ID = i;
}


public String toString(){
return ""+ID;
}
}


class tong{
int index = 0;
mantou[] arrTong = new mantou[6];


public synchronized void push(mantou mt){
if (index == arrTong.length){                                    //判断当tong内的index 馒头数量等于 arrTong 桶的容                                                                                                                量时, this.wait() 停止当前对象上的线程(生产者)。
try{
this.wait();
}catch (Exception e){
}
}
this.notify();
arrTong[index] = mt;
index ++;
}


public synchronized mantou pop(){
if (index == 0){                                                            //判断当tong内的index 馒头数量等于 0时 即桶内没有馒                                                                                                              头时, this.wait() 停止当前对象上的线程(消费者)。
try{
this.wait();
}catch (Exception e){
}
}
this.notify();
index --;
return arrTong[index];
}
}


class chushi implements Runnable {
tong s1 = null;
chushi(tong s1){
this.s1 = s1;
}


public void run(){
for (int i =0;i <=20 ;i++ ){
mantou mt = new mantou(i);
s1.push(mt);
System.out.println("生产者生产了馒头:" + mt);
try{
Thread.sleep(1000);
}catch (InterruptedException e){
}
}
}
}


class xiaofeizhe implements Runnable{
tong s2 = null;


xiaofeizhe(tong s2){
this.s2 = s2;
}


public void run(){
for (int i = 0;i <=20 ;i++ ){
mantou mt = s2.pop();
System.out.println("消费者消费了馒头:" + mt);
try{
Thread.sleep(1000);
}catch (InterruptedException e){
}
}
}


}



总结


Wait   Objcet的方法

Sleep  Thread的方法


Wait  停止线程时放开锁

Sleep 睡眠时不放开锁



线程:一个程序里不同的执行路径

进程:一个class文件 一个exe文件 静态的概念

创建和启动线程的两种方式:从Thread类继承 重写run方法   实现接口

sleep:睡眠

join:

yield:

synchronized:锁定某个对象

wait:睡眠

notify:叫醒wait在某一个对象上的其他线程

notifyAll:叫醒wait在某一个对象上的所有线程

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值