Java多线程学习中遇到的一个有趣的问题

今天随便写了一个线程之间相互调度的程序,代码如下:

class First extends Thread
{
	public First()
	{
		start();
	}
	
	synchronized public void run()
	{
		try
		{
			wait();
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		try
		{
			sleep(2000);
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("hello world~");
	}
}

class Second extends Thread
{
	First first;
	public Second(First first)
	{
		this.first = first;
		start();
	}
	
	synchronized public void run()
	{
		try
		{
			wait();
		}
		catch (InterruptedException e1)
		{
			e1.printStackTrace();
		}
		synchronized( first )
		{
			try
			{
				sleep(2000);
				System.out.println("I'm faster than first~");
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
			first.notifyAll();
		}
	}
}

public class Main
{
	public static void main(String[] args) throws InterruptedException
	{
		First first = new First();
		Second second = new Second(first);
		synchronized( second )
		{
			System.out.println("I'm faster than second~");
			second.notifyAll();
		}
	}
}

本以为输出会很顺畅,但是出现的问题是,只输出了一行:I'm faster than second~

程序就一直处于无响应状态,纠结了好久终于想明白是这么一回事:在main函数中,对second.notifyAll()的调用早于second中的wait()调用(因为是多线程并行,故函数响应时间与代码先后顺序无关),这样先唤醒了second,紧接着second才开始wait,因此就处于无响应状态。

改进方法:只要在second.notifyAll()调用之前空出一点时间先让second的wait调用开始即可,事实上,这段时间如此之短以至于在我电脑上只需要在之前加一行输出语句即可。为了保险起见,还是多加了个sleep,改进后代码如下:


class First extends Thread
{
	public First()
	{
		start();
	}
	
	synchronized public void run()
	{
		try
		{
			wait();
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		try
		{
			sleep(2000);
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("hello world~");
	}
}

class Second extends Thread
{
	First first;
	public Second(First first)
	{
		this.first = first;
		start();
	}
	
	synchronized public void run()
	{
		try
		{
			wait();
		}
		catch (InterruptedException e1)
		{
			e1.printStackTrace();
		}
		synchronized( first )
		{
			try
			{
				sleep(2000);
				System.out.println("I'm faster than first~");
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
			first.notifyAll();
		}
	}
}

public class Main
{
	public static void main(String[] args) throws InterruptedException
	{
		First first = new First();
		Second second = new Second(first);
		System.out.println("wating for all threads prepared~");
		Thread.sleep(2000);
		synchronized( second )
		{
			System.out.println("I'm faster than second~");
			second.notifyAll();
		}
	}
}
输出结果:

wating for all threads prepared~
I'm faster than second~
I'm faster than first~
hello world~


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值