多線程(Java)
阿新 • • 發佈:2018-02-04
out println 子類 sta end cep int 其他 sample
Thread 類 和 Runner 接口
在Java中實現多線程有兩種方法
- 繼承 Thread 類
優點:通過覆蓋Thread 類的方法,可以改變線程的行為。 - 實現 Runner 接口
優點:不需要繼承Thread類,可以繼承其他類。
package threads.samples3;
public class ThreadTest {
public static void main(String[] args) {
// 創建 Thread 子類的實例
Thread1 t1 = new Thread1();
// 創建實現了 Runnable 接口的類的實例,將其作為參數傳給 Thread 類的實例
Thread t2 = new Thread(new Runnable1());
// 通過調用 start 方法啟動線程
t1.start();
t2.start();
}
}
class Thread1 extends Thread {
@Override
public void run() {
for(int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i + " in Thread1");
}
}
}
class Runnable1 implements Runnable {
@Override
public void run() {
for(int i = 0; i < 3; i++) {
try {
Thread.sleep (1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i + " in Runnable1");
}
}
}
/*
0 in Thread1
0 in Runnable1
1 in Runnable1
1 in Thread1
2 in Runnable1
2 in Thread1
*/
多線程(Java)