Posted on 2010-11-08 11:41
セ軍魂ミ 閱讀(535)
評(píng)論(0) 編輯 收藏 所屬分類:
java_多線程
今天剛接觸了java中的多線程,感覺(jué)這方面對(duì)以后很多程序的操作都很有幫助,即相當(dāng)于程序的同時(shí)運(yùn)行。現(xiàn)在就于我對(duì)多線程中Thread類和Runnable接口的初步認(rèn)識(shí),給大家做個(gè)簡(jiǎn)單的認(rèn)識(shí):
1、從JDK文檔中可以發(fā)現(xiàn)Thread類實(shí)際上也是實(shí)現(xiàn)了Runnable;
2、用Thread繼承而來(lái)的線程,一個(gè)線程序?qū)ο笾荒軉?dòng)一次,無(wú)論調(diào)用多少遍start()方法,結(jié)果都只有一個(gè)線程;
注:sart()方法是使該線程開(kāi)始執(zhí)行,java虛擬機(jī)調(diào)用該線程的run()方法,也可以調(diào)用被子類覆蓋寫過(guò)的方法。
3、實(shí)現(xiàn)Runnable接口比繼承Thread類的好處:①適合多個(gè)相同程序代碼的線程去處理同一資源的情況,也能避免由于java
單線程處理帶來(lái)的局限,即處理更為靈活。
②有利于程序的健壯性,能實(shí)現(xiàn)資源的共享。
第一種方式:繼承Thread類
class MyThread extends Thread{
//線程延遲時(shí)間
private int time;
//線程的名字由Thread累自行管理
public MyThread(String name,int time){
//調(diào)用Thread類中的構(gòu)造方法,設(shè)置線程的名字
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()+"-->***正在運(yùn)行***"+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();
}
}
運(yùn)行結(jié)果:
第二方式:實(shí)現(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+"-->***正在運(yùn)行***"+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();
}
}
運(yùn)行結(jié)果:類同于上一種方法的結(jié)果,只是出的順序不相同