码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-10-30 22:38:47      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:java   多线程   wait   

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

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~


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

标签:java   多线程   wait   

原文地址:http://blog.csdn.net/u013687632/article/details/40628189

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!