【 Thread】創建線程的2種方法
阿新 • • 發佈:2018-03-27
Thread run start Runnable (一)Thread類
1.結構
java.lang.Object
|---java.lang.Thread
2.創建線程的兩種方法
(1)一種方法是將類聲明為Thread的子類,該子類應重寫Thread類的run方法
class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } PrimeThread p = new PrimeThread(143); p.start();
(2)創建線程的另一種方法是聲明實現Runnable接口的類,然後該類實現run方法。然後可以分配該類的實例,在創建Thread時作為一個參數來傳遞並啟動
(3)這種方法給已經實現繼承的類,提供了實現多線程的擴展方法,實現接口
class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } PrimeRun p = new PrimeRun(143); new Thread(p).start();
代碼1:第一種創建線程的方法
MyThread類
// 1.繼承Thread類 public class MyThread extends Thread{ private String threadName; public MyThread() { super(); } // 提供一個有參的構造法方法,把名字傳給父類的構造方法直接傳遞一個線程的名字 public MyThread(String threadName) { super(threadName); this.threadName = threadName; } // 2.重寫run方法 @Override public void run() { for(int i=0;i<5;i++) { System.out.println(this.getName()+": hello : "+i); } } }
Main
public class Main { public static void main(String[] args) { //no_parameter_construction_method(); threadName_construction_method(); } /** * 1.調用無參數的構造方法創建線程對象和設置線程名字 * */ public static void no_parameter_construction_method() { // 3.創建線程的實例對象 MyThread my1=new MyThread(); MyThread my2=new MyThread(); // 4.可以設置線程的名字,不設置默認使用JVM給分配的名字(Thread-N) my1.setName("線程1"); my2.setName("線程2"); // 5.啟動線程 // 調用run()的話,的就是單純的調用方法 // 調用線程應該使用start()方法 my1.start(); my2.start(); System.out.println("end"); } public static void threadName_construction_method() { // 3.創建線程的實例對象 MyThread my3=new MyThread("線程3"); MyThread my4=new MyThread("線程4"); // 4.啟動線程 my3.start(); my4.start(); System.out.println("end"); } }
代碼1:第二種創建線程的方法
OurThread類
// 1.實現Runnable接口 public class OurThread implements Runnable{ // 2.重寫run方法 @Override public void run() { for(int i=0;i<10;i++) { // 3.獲取當前線程名字 System.out.println(Thread.currentThread().getName()+": 你好 : "+i); } } }
Main
public class Main { public static void main(String[] args) { // 這2個方法調用,不會等待上一個方法完事後,下一個方法才開始,而是不阻塞直接就開始 createThread(); createNameThread(); } public static void createThread() { // 4.創建實現接口類對象 // 5.創建線程 OurThread ot1=new OurThread(); Thread t1=new Thread(ot1); OurThread ot2=new OurThread(); Thread t2=new Thread(ot2); t1.start(); t2.start(); System.out.println("end"); } public static void createNameThread() { // 4.創建實現接口類對象 // 5.創建線程,可以帶名字,不帶則使用JVM默認分配的名字 OurThread ot1=new OurThread(); Thread t1=new Thread(ot1,"線程01"); OurThread ot2=new OurThread(); Thread t2=new Thread(ot2,"線程02"); t1.start(); t2.start(); System.out.println("end"); } }
【 Thread】創建線程的2種方法