標籤:thread 線程建立
建立繼承Thread的線程
/* * 建立線程方式一:繼承自Thread * 步驟: * 1.自訂類,繼承自Thread類 * 2.重寫run()方法 * 3.建立類的執行個體,即建立一個線程 * 4.調用線程的start()方法,作用:啟動線程、調用run()方法 * * * Thread的run方法,用於儲存線程要執行的代碼,必須重寫此方法 * 啟動線程時會自動調用此方法 */class Demo extends Thread{ @Override public void run() { for(int i=1;i<=50;i++){ System.out.println("*****run*******"+i); } }}public class Test01 { public static void main(String[] args) { Demo demo=new Demo();//建立一個線程 demo.start();//啟動線程並執行該線程的run方法 //demo.run();僅僅是調用對象的方法,線程雖然建立了,但並未啟動 for(int i=1;i<=50;i++){ System.out.println("*****Hello World*******"+i); } }}
建立兩個線程
/* * 建立兩個線程 * * 線程預設名稱 * 自訂線程:Thread-編號,從0開始 * 主線程:main * * 查看線程名稱 * getName() * Thread.currentThread() 擷取當前線程執行個體 * * 設定線程名稱 * 通過構造方法、 * */class MyThread extends Thread { public MyThread(String name){ super(name); } @Override public void run() { System.out.println(Thread.currentThread()==this); for (int i = 1; i <= 50; i++) { //System.out.println(getName()+"*****run*******" + i); System.out.println(Thread.currentThread().getName()+"*****run*******" + i); } }}public class Test02 { public static void main(String[] args) { // 建立兩個線程並啟動 MyThread t1 = new MyThread("線程一"); MyThread t2 = new MyThread("線程二"); t1.setName("first"); t1.start(); t2.start(); Thread thread=Thread.currentThread();//擷取當前線程執行個體 for (int i = 1; i <= 50; i++) { System.out.println(thread.getName()+"*****Hello World*******" + i); } }}
JAVA學習筆記(三十七)- 建立繼承Thread的線程