多线程面试题:子线程循环10次,接着主线程循环100次;接着回到子线程循环10次,然后再回到主线程循环100次,如此交替50次。

本文探讨了并发编程中的线程同步机制,通过实例展示了使用wait和notify方法实现线程间的协调与通信,强调了在wait方法中使用while循环的重要性以避免假唤醒等问题。

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

public static void main(String[] args){
	final Business b = new Business();
	new Thread(){
		@Override
		public void run(){
			for(int i=1; i<=50; i++){
				b.sub(i);
			}
		}
	}.start();
	
	
	for(int i=1; i<=50; i++){
		b.main(i);
	}
}
class Business{
	private boolean bShouldSub = true;
	public synchronized void main(int i){
		while(bShouldSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int j=1; j<=100; j++){
			System.out.println(Thread.currentThread().getName() + ", loop times: " + j + " of " + i);
		}
		bShouldSub = true;
		this.notify();
	}
	public synchronized void sub(int i){
		while(!bShouldSub){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int j=1; j<=10; j++){
			System.out.println(Thread.currentThread().getName() + ", loop times: " + j + " of " + i);
		}
		bShouldSub = false;
		this.notify();
	}
}


注意:在wait一定放在while循环里,不要用if来判断条件,防止假唤醒(比如interrupt或者timeout),参见wait方法的jdk描述:

  • A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

         synchronized (obj) {
             while (<condition does not hold>)
                 obj.wait(timeout);
             ... // Perform action appropriate to condition
         }
     
    (For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001). 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值