?? suspend.java
字號:
//掛起、開啟、停止一個線程
class MyThread implements Runnable{
Thread thrd;
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()+" 開始。");
try{
for(int i=1; i<1000;i++){
System.out.print(i+" ");
if((i%10)==0){
System.out.println();
Thread.sleep(250);
}
//用同步塊檢查suspended stopped.
synchronized(this){
while(suspended){
wait();
}
if(stopped) break;
}
}
}catch(InterruptedException e){
System.out.println(thrd.getName()+" 被打斷。");
}
System.out.println(thrd.getName()+" 退出。");
}
//停止線程
synchronized void myStop(){
stopped = true;
//接著讓一個掛起的線程停止。
suspended = false;
notify();
}
synchronized void mySuspended(){
suspended = true;
}
//開啟線程
synchronized void myResuse(){
suspended = false;
notify();
}
}
public class Suspend {
public static void main(String args[]){
MyThread ob1 = new MyThread("我的線程");
try{
Thread.sleep(1000);
ob1.mySuspended();
System.out.println("掛起線程");
Thread.sleep(1000);
ob1.myResuse();
System.out.println("開啟線程");
Thread.sleep(1000);
ob1.mySuspended();
System.out.println("掛起線程");
Thread.sleep(1000);
ob1.myResuse();
System.out.println("開啟線程");
Thread.sleep(1000);
ob1.mySuspended();
System.out.println("停止線程");
ob1.myStop();
}catch(InterruptedException e){
System.out.println("主線程被打斷。");
}
//等待線程結束
try{
ob1.thrd.join();
}catch(InterruptedException e){
System.out.println("主線程被打斷。");
}
System.out.println("主線程結束。");
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -