java執行緒建立的兩種方式

ustcyy91發表於2016-11-30

java執行緒建立有兩種方式

1)繼承Thread類

2)實現runnable介面

具體例子:

1)繼承Thread類

package demo.example.com;


public class threadtest2 {


public static void main(String[] args) {
Computer2 t=new Computer2();
Computer3 t1=new Computer3();
t.start();
t1.start();
}


}
class Computer2 extends Thread{
public void run(){
for(int i=0;i<10;i++)
System.out.println("這個數字是"+i);
}
}
class Computer3 extends Thread{
public void run(){
for(int i=0;i<10;i++)
System.out.println(i);
}
}


2.實現runnable 介面

package demo.example.com;


public class threadtest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Computer c=new Computer();
Computer1 c1=new Computer1();
Thread t=new Thread(c);
Thread t1=new Thread(c1);//建立執行緒的語句,其中括號內是實現runnable介面的的例項!!

t.start();
t1.start();
}


}
class Computer implements Runnable{


@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println("這個數字是"+i);

}


}
class Computer1 implements Runnable{


@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println(i);

}


}


Runnable 介面的定義:

public interface Runnable

{

public abstract void run();

}

相關文章