import java.lang.Thread;
import java.lang.Runnable;
import java.util.Date;
public class DefineAndStartThread{
class ThreadA extends Thread{
private Date runDate;
//繼承Thread的子類必須實現run方法,Thread中的run方法未做任何事
public void run(){
System.out.println("ThreadA begin");
this.runDate = new Date();
System.out.println("ThreadA run: "+this.runDate);
System.out.println("ThreadA end");
}
}
class ThreadB implements Runnable{
private Date runDate;
public void run(){
System.out.println("ThreadB begin");
this.runDate = new Date();
System.out.println("ThreadB run: "+this.runDate);
System.out.println("ThreadB end");
}
}
public void startThreadA(){
//這里是面向對象的多態特征,子類對象可以直接賦給父類變量,但運行時依然表現為子類特性
//聲明變量類型為父類,實際變量類型為子類對象
Thread threadA = new ThreadA();
//啟用線程后,jvm會調用該線程的run方法,執行線程
threadA.start();
}
public void startThreadB(){
Runnable rb = new ThreadB();
Thread threadB = new Thread(rb);
//啟用線程后,會引起調用該線程的run方法,執行線程
threadB.start();
}
public static void main(String[] args){
DefineAndStartThread test = new DefineAndStartThread();
test.startThreadA();
test.startThreadB();
}
}
import java.lang.Thread; import java.util.Date; public class StopThread{ //因為該類的start、stop、main方法都要用到ThreadA的實例對象,所以聲明為類變量 private ThreadA thread = new ThreadA(); class ThreadA extends Thread{ //用來對外設置是否執行run方法的標識 private boolean running = false; private Date runDate; //重寫Thread父類的start方法,在父類start方法之上設置運行標識為true public void start(){ this.running = true; super.start(); } //線程一旦啟動則不停的循環執行,直到執行標識為false,則停止運行 public void run(){ System.out.println("ThreadA begin"); try{ int i=0; while(this.running){ this.runDate = new Date(); // System.out.println("ThreadA run: "+this.runDate); System.out.println("ThreadA run: "+ i++); Thread.sleep(200); } }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("ThreadA end"); } public void setRunning(boolean running){ this.running = running; } } public void start(){ this.thread.start(); } //修改執行標識為false則停止執行run方法 public void stop(){ this.thread.setRunning(false); } public static void main(String[] args){ StopThread stopThread = new StopThread(); //線程一直運行直到結果結束 stopThread.start(); //當前線程休眠1秒 try{ Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); } stopThread.stop(); } }
