线程通信的方法

线程通信

wait(); notify(); / notifyAll();

1. wait();

一旦执行此方法,当前线程进入阻塞状态,并释放同步监视器(锁)。

2.notify();

一旦执行该方法,就会唤醒wait的一个线程,如果有多个线程,就会唤醒优先级高的线程。

3.notifyAll();

一旦执行此方法,就会唤醒所有的wait的线程。

public class Demo003 extends Thread{
private int sum=1;
public void run(){
while(true){
synchronized(this){
notifyAll();
if (sum<=100){
System.out.println(Thread.currentThread().getName()+sum);
sum++;
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
break;
}
}

    }
}

}
class A {
public static void main(String[] args) {
Demo003 demo003 = new Demo003();
Thread thread2= new Thread(demo003);
Thread thread1 = new Thread(demo003);
thread1.setName(“1-”);
thread2.setName(“2-”);
thread2.start();
thread1.start();

}

}
在这里插入图片描述
在这里插入图片描述
再锁的位置不使用与wait相同的对象的时候会报错
public class Demo003 extends Thread{
private int sum=1;
public void run(){
while(true){
synchronized(Demo003.class){//用当前类做锁
notifyAll();//demo003调用的 notifyAll();
if (sum<=100){
System.out.println(Thread.currentThread().getName()+sum);
sum++;
try {
wait();//demo003调用的 wait()
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
break;
}
}

    }
}

}
class A {
public static void main(String[] args) {
Demo003 demo003 = new Demo003();
Thread thread2= new Thread(demo003);
Thread thread1 = new Thread(demo003);
thread1.setName(“1-”);
thread2.setName(“2-”);
thread2.start();
thread1.start();

}

}
在这里插入图片描述

锁和调用notify与调用wait的对象必须一致
public class Demo003 extends Thread{
private int sum=1;
public void run(){
while(true){
synchronized(Demo003.class){//使用Demo003.class做锁
Demo003.class.notifyAll();Demo003.class做调用notify对象
if (sum<=100){
System.out.println(Thread.currentThread().getName()+sum);
sum++;
try {
Demo003.class.wait();Demo003.class做调用wait对象
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
else {
break;
}
}

    }
}

}
class A {
public static void main(String[] args) {
Demo003 demo003 = new Demo003();
Thread thread2= new Thread(demo003);
Thread thread1 = new Thread(demo003);
thread1.setName(“1-”);
thread2.setName(“2-”);
thread2.start();
thread1.start();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值