Java的多线程-线程间的通信(5)

本文详细解析了Java中wait(), notify(), 和synchronized的作用及使用方法,并对比了它们与suspend(), resume(), sleep()的区别。通过示例代码展示了如何正确使用这些方法来实现线程间的同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.2 wait()、notify()和synchronized

 

waite()和notify()因为会对对象的“锁标志”进行操作,所以它们必须在synchronized函数或synchronized block中进行调用。如果在non-synchronized函数或non-synchronized block中进行调用,虽然能编译通过,但在运行时会发生IllegalMonitorStateException的异常。

例18:

class TestThreadMethod extends Thread{

public int shareVar = 0;

public TestThreadMethod(String name){

super(name);

new Notifier(this);

}

public synchronized void run(){

if(shareVar==0){

for(int i=0; i<5; i++){

shareVar++;

System.out.println("i = " + shareVar);

try{

System.out.println("wait......");

this.wait();

}

catch(InterruptedException e){}

}}

}

}

class Notifier extends Thread{

private TestThreadMethod ttm;

Notifier(TestThreadMethod t){

ttm = t;

start();

}

public void run(){

while(true){

try{

sleep(2000);

}

catch(InterruptedException e){}

/*1 要同步的不是当前对象的做法 */

synchronized(ttm){

System.out.println("notify......");

ttm.notify();

}}

}

}

public class TestThread{

public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

t1.start();

}

}

运行结果为:

i = 1

wait......

notify......

i = 2

wait......

notify......

i = 3

wait......

notify......

i = 4

wait......

notify......

i = 5

wait......

notify......

4. wait()、notify()、notifyAll()和suspend()、resume()、sleep()的讨论

4.1 这两组函数的区别

1) wait()使当前线程进入停滞状态时,还会释放当前线程所占有的“锁标志”,从而使线程对象中的synchronized资源可被对象中别的线程使用;而suspend()和sleep()使当前线程进入停滞状态时不会释放当前线程所占有的“锁标志”。

2) 前一组函数必须在synchronized函数或synchronized block中调用,否则在运行时会产生错误;而后一组函数可以non-synchronized函数和synchronized block中调用。

4.2 这两组函数的取舍

Java2已不建议使用后一组函数。因为在调用wait()时不会释放当前线程所取得的“锁标志”,这样很容易造成“死锁”。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值