final void resume() //重启(继续执行)
final void suspend() //暂停(挂起)
final void stop() //停止
说明:这三个方法在Java2中就被摒弃了,无法继续使用来控制线程。
但是线程的设计必须有一个run()方法来周期性的检查他,以确定线程是否应该挂起、继续执行还是停止。通常,这是依靠两个指标变量来完成的。一个用于挂起和继续执行,另一个用于停止。
public class MyThread5 implements Runnable{
Thread thread;
boolean suspended;
boolean stopped;
MyThread5(String name) {
thread = new Thread(this, name);
suspended = false;
stopped = false;
}
public static MyThread5 cteateAndStart(String name) {
MyThread5 myThread = new MyThread5(name);
myThread.thread.start();
return myThread;
}
public void run() {
System.out.println(thread.getName() + " starting.");
try {
for (int i = 1; i < 1000; i++) {
System.out.print(i + " ");
if ((i%10)==0) {
System.out.println();
Thread.sleep(250);
}
synchronized(this) {
while (suspended) {
wait();
}
if (stopped) break;
}
}
}catch (InterruptedException exception) {
System.out.println(thread.getName() + " interrupted.");
}
System.out.println(thread.getName() + " exiting.");
}
//停止执行线程
synchronized void mystop() {
stopped = true;
suspended = false;
notify();
}
//暂停
synchronized void mysusposend() {
suspended = true;
}
//继续执行
synchronized void myresume() {
suspended = false;
notify();
}
}
public class Suspended {
public static void main(String[] args) {
MyThread5 mt1 = MyThread5.cteateAndStart("My Thread");
try {
Thread.sleep(1000);
mt1.mysusposend();
System.out.println("Suspendeding thread.");
Thread.sleep(1000);
mt1.myresume();
System.out.println("Resuming thread.");
Thread.sleep(1000);
mt1.mysusposend();
System.out.println("Suspendeding thread.");
Thread.sleep(1000);
mt1.myresume();
System.out.println("Resuming thread.");
Thread.sleep(1000);
//mt1.mystop();
mt1.mysusposend();
System.out.println("Stopping thread.");
mt1.mystop();
}catch (InterruptedException exception) {
System.out.println("Main thread Interrupted.");
}
try {
mt1.thread.join();
}catch (InterruptedException exception) {
System.out.println("Main thread Interrupted.");
}
System.out.println("Main thread exiting.");
}
}
通过控制参数的boolean值来实现



