java多线程之线程状态(2)

转载请注明出处

http://blog.csdn.net/pony_maggie/article/details/43206445


作者:小马


来看suspend和resume机制造成的阻塞现象。需要明确一点,suspend和resume在jdk1.6以后就不推荐使用了。这里只为了说明原理。


Blockable和Peeker依然是通用测试类,新增了两个类,分别为SuspendResume1和SuspendResume2。与上一篇类似,两个类的唯一区别在于run函数:

class SuspendResume1 extends SuspendResume
{
	public SuspendResume1(Container c) {super(c);}
	public synchronized void run()
	{
		while(true)
		{
			i++;
			update();
			suspend();
		}
	}
}
class SuspendResume2 extends SuspendResume
{
	public SuspendResume2(Container c)
	{
		super(c);
	}
	public void run()
	{
		while(true)
		{
			change();
			suspend();
		}
	}
	
	public synchronized void change()
	{
		i++;
		update();
	}
}

这里不多说了,运行的效果如下:

java多线程之线程状态(2)_第1张图片

SuspendResume2中的value才会和文本框里的计数器同步。


两个类通过suspend来让自己阻塞,从而其它线程才有机会执行,不过这里有些区别,不像sleep在睡眠一定时间会自动唤醒,suspend的线程必须要resume才能唤醒,这就是Resumer类的作用,它也是一个线程,每隔1s就让SuspendResume实例唤醒自己。

class Resumer extends Thread
{
	private SuspendResume sr;
	public Resumer(SuspendResume sr)
	{
		this.sr = sr;
		start();
	}
	
	public void run()
	{
		while(true)
		{
			try 
			{
				sleep(1000);
			} 
			catch (InterruptedException e) 
			{
				// TODO: handle exception
				System.err.println("Interrupted");
			}
			sr.resume();
		}
	}
	
}





你可能感兴趣的:(java,线程,synchronized,resume,suspend)