高併發學習1--執行緒的基礎
阿新 • • 發佈:2018-12-12
執行緒的實現
繼承Thread類
必須重寫run()方法
class MyThread extends Thread{
private static int num = 0;
public MyThread(){
num++;
}
@Override
public void run() {
System.out.println("主動建立的第"+num+"個執行緒");
}
}
建立好了自己的執行緒類之後,就可以建立執行緒物件了,然後通過start()方法去啟動執行緒。注意,不是呼叫run()方法啟動執行緒,run方法中只是定義需要執行的任務,如果呼叫run方法,即相當於在主執行緒中執行run方法,跟普通的方法呼叫沒有任何區別
public class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread{
private static int num = 0;
public MyThread(){
num++;
}
@Override
public void run() {
System.out.println("主動建立的第"+num+"個執行緒");
}
}
在上面程式碼中,通過呼叫start()方法,就會建立一個新的執行緒了。為了分清start()方法呼叫和run()方法呼叫的區別,請看下面一個例子:
public class Test {
public static void main(String[] args) {
System.out.println("主執行緒ID:"+Thread.currentThread().getId());
MyThread thread1 = new MyThread("thread1");
thread1.start();
MyThread thread2 = new MyThread("thread2");
thread2.run();
}
}
class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
System.out.println("name:"+name+" 子執行緒ID:"+Thread.currentThread().getId());
}
}
執行結果: 從輸出結果可以得出以下結論:
1)thread1和thread2的執行緒ID不同,thread2和主執行緒ID相同,說明通過run方法呼叫並不會建立新的執行緒,而是在主執行緒中直接執行run方法,跟普通的方法呼叫沒有任何區別;
2)雖然thread1的start方法呼叫在thread2的run方法前面呼叫,但是先輸出的是thread2的run方法呼叫的相關資訊,說明新執行緒建立的過程不會阻塞主執行緒的後續執行。
實現Runnable介面
必須重寫run()方法 在Java中建立執行緒除了繼承Thread類之外,還可以通過實現Runnable介面來實現類似的功能。實現Runnable介面必須重寫其run方法。 下面是一個例子:
public class Test {
public static void main(String[] args) {
System.out.println("主執行緒ID:"+Thread.currentThread().getId());
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
class MyRunnable implements Runnable{
public MyRunnable() {
}
@Override
public void run() {
System.out.println("子執行緒ID:"+Thread.currentThread().getId());
}
}