从头认识多线程-1.10 暂停与恢复线程

这一章节我们来讨论一下暂停与恢复线程,也就是resume与suspend

1.代码清单

package com.ray.deepintothread.ch01.topic_10;

public class RusumeAndSuspend {
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws InterruptedException {
		ThreadFive threadFive = new ThreadFive();
		Thread thread = new Thread(threadFive);
		thread.start();
		Thread.sleep(50);
		thread.suspend();
		System.out.println(System.currentTimeMillis() + " " + threadFive.getCount());
		Thread.sleep(50);
		System.out.println(System.currentTimeMillis() + " " + threadFive.getCount());
		Thread.sleep(50);
		thread.resume();
		System.out.println(System.currentTimeMillis() + " " + threadFive.getCount());
	}
}

class ThreadFive implements Runnable {

	private int count = 0;

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	@Override
	public void run() {
		while (true) {
			count++;
		}
	}
}

输出:

1460854142843 17375185
1460854142890 17375185
1460854142953 17382422

(程序继续运行)


从上面的输出可以看见,suspend后,第一第二次的count是一样的,表示线程的确已经停止计算,当我们resume之后,线程有恢复过来,但是,使用这两个方法会出现很大的问题,这些我们会在后面的章节讨论。


总结:这一章节主要展示了resume与suspend的使用,后面继续会讲到它们的隐患。


我的github:https://github.com/raylee2015/DeepIntoThread



你可能感兴趣的:(多线程)