您的位置:首页 > 编程语言 > Java开发

Java 多线程使用:线程的挂起与重新唤醒

2013-09-27 20:19 519 查看
这两天在研究多线程的使用方法,我们的需求是这样的:程序启动时,先让子线程处于运行状态,运行过程中会人为的更改该线程的运行状态为挂起,等待随机的时长之后,再把该线程重新唤醒,让其继续运行;人为挂起线程和恢复线程的次数也是随机的。经过不懈努力,最终找到了如下壹個实现了 Runnable 的线程类,完美解决该问题,记录于此。首先是 MyThread 线程类的定义:
public class MyThread implements Runnable {

private boolean running = false;
private boolean waiting = false;
private Thread thread;
private String name;

public MyThread(String name) {
this.name = name;
this.thread = new Thread(this);
}

//启动线程
public void start() {
running = true;
thread.start();
}

//挂起线程
public void suspend() {
if (waiting) {
return;
}
synchronized (this) {
this.waiting = true;
}
}

//恢复线程
public void resume() {
if (!waiting) {
return;
}
synchronized (this) {
this.waiting = false;
this.notifyAll();
}
}

//终止线程
public void stop() {
if (!running) {
return;
}
synchronized (this) {
running = false;
}
}

public void run() {
while (true) {
try {
// 线程挂起和退出处理
synchronized (this) {
if (!running) {
break;
}
if (waiting) {
this.wait();
}
}
// 应该做的事情
execute();
// 进入等待状态
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

//真正要做的事情
private void execute() {
if(running && !waiting){
System.out.println(name + " is running...");
}
}
}


上述代码中,MyThread 类提供了四個 public 的方法,分别是 start(),suspend(),resume(),stop(),分别完成启动线程,挂起线程,恢复线程,终止线程的功能,程序通过两個布尔型变量控制子线程 thread 的状态:waiting 和 running,彼此之间配合堪称天衣无缝, 多线程果然强大。

接下来是调用该线程类的测试代码:

public class Main {
public static void main(String[] args) {
try {
MyThread dog = new MyThread("test");
System.out.println("--- start the subthread");
dog.start();
Thread.sleep(500);
System.out.println("--- suspend the thread");
dog.suspend();
System.out.println("--- main thread do something");
Thread.sleep(500);
System.out.println("--- resume the thread");
dog.resume();
Thread.sleep(500);
System.out.println("--- end this thread");
dog.stop();
System.out.println("--- main thread do something");
Thread.sleep(100);
System.out.println("--- exit programe.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


该类运行之后的输出结果为:
--- start the subthread
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
--- suspend the thread
--- main thread do something
--- resume the thread
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
test is running...
--- end this thread
--- main thread do something
--- exit programe.


从输出可以很容易的看出,从第13行开始,子线程被挂起之后,就不再执行 execute() 方法并打印字符串了,等到第15行时主线程重新把它激活之后,又开始继续输出字符串了,到最后第26行主线程把子线程结束掉之后,它就不再运行了,之后主线程自行退出了,整個过程中,子线程的状态按照我们的要求发生了数次改变,效果让人满意。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: