(一)Thread類java
1.結構多線程
java.lang.Objectide
|---java.lang.Threadthis
2.建立線程的兩種方法
spa
(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類get
// 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"); } }