|
因?yàn)镴ava只支持單繼承,如果已經(jīng)繼承了一個(gè)類,就不能再繼承Thread類了,此時(shí),要實(shí)現(xiàn)多繼承,可以實(shí)現(xiàn)Runnable接口。 1、Runnable接口 Runnable接口就是為實(shí)現(xiàn)多線程的,它里面只聲明了一個(gè)run()方法,聲明如下: public interface Runnable { public abstract void run(); } 線程對象必須實(shí)現(xiàn)此run()方法來描述線程的所有活動及執(zhí)行的操作,已實(shí)現(xiàn)的run()方法稱為該線程對象的線程體。 2、示例 以上一篇的例子為例,改寫為實(shí)現(xiàn)Runnable方法。 其完整代碼如下: public class ThreadLearn implements Runnable{ int start,end; public ThreadLearn(int start,int end) {//此為構(gòu)造方法,因?yàn)闆]有繼承,所以不需super() this.start=start; this.end=end; } public void run() {//此為Runnable接口中的方法,可以被多個(gè)線程使用 System.out.println("當(dāng)前線程是:"+Thread.currentThread().getName()); while(start<=end) { for(int i=1;i<=10;i++) { System.out.print(start+" "); start=start+2; } System.out.println(); } } public static void main(String args[]) { System.out.println("當(dāng)前線程是:"+Thread.currentThread().getName()); ThreadLearn target1=new ThreadLearn(1,100);//創(chuàng)建類的一個(gè)對象 ThreadLearn target2=new ThreadLearn(2,100); Thread odd=new Thread(target1,"奇數(shù)");//創(chuàng)建線程類的對象,target1為線程的目標(biāo)對象,線程名為“奇數(shù)” Thread even=new Thread(target2,"偶數(shù)");//創(chuàng)建線程類的對象,target2為線程的目標(biāo)對象,線程名為“偶數(shù)” odd.start();//啟動線程 even.start(); } } 其運(yùn)行結(jié)果如下: 如果多運(yùn)行幾次,結(jié)果可能會不一樣。 但是也有可能結(jié)果是一樣的,由于線程的并發(fā)執(zhí)行性,它的運(yùn)行結(jié)果會有點(diǎn)“任性”。 |
|
|