⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 suspend.java

📁 Java 程序设计源码 只提供了部分
💻 JAVA
字号:
class MyThread implements Runnable {  Thread thrd;  //volatile  关键字 用于 同步对变量的修改  volatile boolean suspended;  volatile boolean stopped;  MyThread(String name) {    thrd = new Thread(this, name);    suspended = false;    stopped = false;    thrd.start();  }  public void run() {    System.out.println(thrd.getName() + "is started.");    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 e) {      System.out.println(thrd.getName() + " was interrupted.");    }    System.out.println(thrd.getName() + " exit.");  }  synchronized void myStop() {    stopped = true;    suspended = false;    notify();  }  synchronized void mySuspended() {    suspended = true;  }  synchronized void myResume() {    suspended = false;    notify();  }}public class Suspend {  public static void main(String[] args) {    MyThread obl = new MyThread("My Thread ");    try {      Thread.sleep(1000);      obl.mySuspended();      System.out.println("Thread is suspended.");      Thread.sleep(1000);      obl.myResume();      System.out.println("Thread is started.");      Thread.sleep(1000);      obl.mySuspended();      System.out.println("Thread is suspended.");      Thread.sleep(1000);      obl.myResume();      System.out.println("Thread is started.");      Thread.sleep(1000);      obl.mySuspended();      System.out.println("Thread was stoped.");      obl.myStop();    }    catch(InterruptedException e) {      System.out.println("main Thread was interrupted.");    }    try {      //MyThread 类 是 实现 Runnable 接口的。需要调用 Thread 实例 thrd 来吧 线程加入 运行      obl.thrd.join();    }    catch(InterruptedException e) {      System.out.println("main Thread was interrupted.");    }    System.out.println("main Thread was stopped.");  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -