创建项目suspend_resume_test,文件MyThread代码如下:
package mythread;
public class MyThread extends Thread {
private long i = 0;
public long getI() {
return i;
}
public void setI(long i) {
this.i = i;
}
@Override
public void run() {
while (true) {
i++;
}
}
}
文件Run.java代码如下:
package test.run;
import mythread.MyThread;
public class Run {
public static void main(String[] args) throws InterruptedException {
try {
MyThread myThread = new MyThread();
System.out.println("线程开始执行");
myThread.start();
Thread.sleep(3000);
System.out.println(myThread.getI());
System.out.println(myThread.getI());
System.out.println("线程暂停执行");
myThread.suspend();
System.out.println("A=" + System.currentTimeMillis() + " i=" + myThread.getI());
Thread.sleep(3000);
System.out.println("A=" + System.currentTimeMillis() + " i=" + myThread.getI());
System.out.println("线程恢复执行");
myThread.resume();
System.out.println(myThread.getI());
System.out.println(myThread.getI());
Thread.sleep(3000);
System.out.println("线程暂停执行");
myThread.suspend();
System.out.println("B=" + System.currentTimeMillis() + " i=" + myThread.getI());
Thread.sleep(3000);
System.out.println("B=" + System.currentTimeMillis() + " i=" + myThread.getI());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
程序运行后的结果如下:
线程开始执行
2185737846
2185793292
线程暂停执行
A=1653834350323 i=2185874251
A=1653834353323 i=2185874251
线程恢复执行
4387175149
4387217064
线程暂停执行
B=1653834356324 i=4387272762
B=1653834359325 i=4387272762
从控制台的输出我们可以很清楚地看到:在开始和暂停之间的两次次输出是不同的,说明线程正在运行;在暂停和恢复之间的两次输出是一样的,说明线程已暂停;在恢复之后的两次输出是不同的,说明线程已恢复执行。
在使用 suspend 与 resume 方法时,如果使用不当,极易造成公共的同步对象的独占,使得其他线程无法访问公共同步对象。
在使用 suspend 与 resume 方法时也容易出现因为线程的暂停而导致数据不同步的情况。
以上代码下载请点击该链接:https://github.com/Yarrow052/Java-package.git