1.目的
創建線程,即拿到一個線程實例。這個線程實例必須具備開啟、等待、喚醒等控制自身生命周期的方法。
2.創建Thread線程
方式一:new Thread()、new Thread(String name)
1 /** 2 *兩個構造器也有區別:線程名不同 3 */ 4 public class Thread implements Runnable { 5 private char name[]; 6 7 //1.不帶參 8 /* 9 *Automatically generated names are of the form *"Thread-"+n, where n is an integer 10 */ 11 public Thread() { 12 init(null, null, "Thread-" + nextThreadNum(), 0); 13 } 14 private static synchronized int nextThreadNum() { 15 return threadInitNumber++; 16 } 17 //2.帶參 18 public Thread(String name) { 19 init(null, null, name, 0); 20 } 21 //初始化線程—init()? 22 private void init(ThreadGroup g, Runnable target, String name,long stackSize) { 23 init(g, target, name, stackSize, null); 24 } 25 private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc) { 26 if (name == null) { 27 throw new NullPointerException("name cannot be null"); 28 } 29 this.name = name.toCharArray(); 30 /**後面是初始化線程代碼—略*/ 31 } 32 }
方式二:new Thread(Runnable run)、new Thread(Runnable run,String name)
public interface Runnable {
public abstract void run();
}
/* *用“外置Runnable對象”覆蓋、取代當前對象(目的是讓注入對象也能擁有Thread對象的管理線程的方法) */ public class Thread implements Runnable { private Runnable target; public void run() { if (target != null) { target.run(); //調用“外置線程對象”的run()方法 } //除去run()的其它方法,針對的對象都是Thread.currentThread() }
3.創建自定義線程
方式一:繼承java.lang.Thread
/**
*1.構造類
*/
public class MyThread extends Thread { //@Override //是否覆蓋父類對象的run()方法 public void run() { //do something } } /**
*2.創建實例
*/ public class Main{ public void static void main(String args){ Thread t =new MyThread(); //創建Thread線程——>方式一
t.run(); //t的run()被調用
} }
方法二:實現Runnable接口
public class MyThread implements Runnable { public run() { //do something }
public class Main{ public void static void main(String args){
MyThread mt =new MyThread();
Thread t =new Thread(mt); //創建Thread線程——>方式二 ——————>Thread.currentThread() =>main || this對象 =>t || t的<init>被調用
t.run(); ——————>Thread.currentThread() =>t || this對象 =>t || mt的run()被調用
/**因為除去run()的其它方法,針對的對象都是Thread.currentThread(),所以*/
t.start(); ——————>Thread.currentThread() =>t || this對象 =>t || t的start()被調用
t.stop(); ——————>Thread.currentThread() =>t || this對象 =>t || t的stop()被調用
}
}
4.資源共享性
例: class MyThread——>private int i =5;
方式一:不共享
public class MyThread extends Thread {
private int i =5; public void run() { i--;
while(i>0){
System.out.println(this.currentThread().getName()+":"+i);
} } }
public class Main{ public void static void main(String args){ Thread t1 =new MyThread("t1");
Thread t2 =new MyThread("t2");
t1.start();
t2.start();
}
}
/**輸出:
*t1:4
*t2:4
*t1:3
*t2: 3
* ....
*/
方式二:共享
(實現Runnable接口方式)略
原因:
private native void start0()