Posted on 2010-11-08 11:41
セ軍魂ミ 閱讀(527)
評論(0) 編輯 收藏 所屬分類:
java_多線程
今天剛接觸了java中的多線程,感覺這方面對以后很多程序的操作都很有幫助,即相當于程序的同時運行。現(xiàn)在就于我對多線程中Thread類和Runnable接口的初步認識,給大家做個簡單的認識:
1、從JDK文檔中可以發(fā)現(xiàn)Thread類實際上也是實現(xiàn)了Runnable;
2、用Thread繼承而來的線程,一個線程序對象只能啟動一次,無論調(diào)用多少遍start()方法,結果都只有一個線程;
注:sart()方法是使該線程開始執(zhí)行,java虛擬機調(diào)用該線程的run()方法,也可以調(diào)用被子類覆蓋寫過的方法。
3、實現(xiàn)Runnable接口比繼承Thread類的好處:①適合多個相同程序代碼的線程去處理同一資源的情況,也能避免由于java
單線程處理帶來的局限,即處理更為靈活。
②有利于程序的健壯性,能實現(xiàn)資源的共享。
第一種方式:繼承Thread類
class MyThread extends Thread{
//線程延遲時間
private int time;
//線程的名字由Thread累自行管理
public MyThread(String name,int time){
//調(diào)用Thread類中的構造方法,設置線程的名字
super(name);
this.time=time;
}
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.printMsg();
}
}
public void printMsg(){
System.out.println (Thread.currentThread().getName()+"-->***正在運行***"+this.time+"秒");
}
}
public class Demo {
public static void main(String[] args){
MyThread mt = new MyThread("AA",100);
MyThread mt1 = new MyThread("BB",200);
MyThread mt2 = new MyThread("CC",300);
mt.start();
mt1.start();
mt2.start();
}
}
運行結果:
第二方式:實現(xiàn)Ruanable接口
class MyThread1 implements Runnable{
private String name;
private int time;
public MyThread1(String name,int time){
this.name= name;
this.time=time;
}
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.printMsg();
}
}
public void printMsg(){
System.out.println (this.name+"-->***正在運行***"+this.time+"秒");
}
}
public class DemoF {
public static void main(String[] args){
MyThread mt = new MyThread("AA",100);
MyThread mt1 = new MyThread("BB",200);
MyThread mt2 = new MyThread("CC",300);
mt.start();
mt1.start();
mt2.start();
}
}
運行結果:類同于上一種方法的結果,只是出的順序不相同