標籤:多線程
建立線程的兩種方式繼承Thread類
- 定義一個類繼承Thread類
- 子類中重寫Thread類中的run方法
- 建立Thread子類的對象,就是建立了線程對象
- 調用線程對象的start方法,啟動線程,會自動調用run方法
public class TestThread extends Thread { public static void main(String[] args) { TestThread tt = new TestThread(); tt.start(); } //重寫run方法 public void run() { System.out.println("run"); }}
實現Runnable介面
- 自已子類實現Runnable介面
- 重寫介面中的run方法
- 通過Thread含參構造器建立線程對象
- 將Runnable介面子類的對象作為實參傳遞
- 調用Thread類的start方法,開啟線程
public class TestThread { public static void main(String[] args) { T t = new T(); Thread tt = new Thread(t); tt.start(); }}class T implements Runnable { @Override public void run() { System.out.println("run"); }}
應該多使用Runnable介面實現多線程,可以實現多繼承
String getName();返回當前線程void setName(String name);//設定線程名字static currentThread();//返回當前線程
setPriority(int new);//改變線程的優先順序getPriority()返回線程的優先順序
Thread.sleep(10);//讓線程睡10秒,阻塞
線程同步
synchroized(對象) { //需要同步的代碼}
public synchroinized void show(String name) { ...}
線程通訊
wait();//讓當前線程等待notify();//喚醒線程notifyAll();//喚醒正在排隊的所有線程
【Java總結-線程】Java多線程的使用