與每個java語言中的元素一樣,線程是對象。在Java中,我們有兩種方式創建線程:
1、通過直接繼承thread類,然后覆蓋run方法。
2、構建一個實現Runnable接口的類,然后創建一個thread類對象并傳遞Runnable對象作為構造參數
代碼如下:
public class Calculator implements Runnable{ private int number; public Calculator(int number){ this.number = number; } /** * run()方法是創建的線程執行指令 */ @Override public void run() { for (int i = 1; i < 10; i++) { System.out.printf("%s:%d*%d=%d\n",Thread.currentThread().getName(),number,i,i*number); } } public static void main(String[] args) { for (int i = 1; i < 10; i++) { Calculator cal = new Calculator(i); Thread thread = new Thread(cal); thread.start(); } } }
3、每個Java程序最少有一個執行線程。當你運行程序的時候,JVM運行負責調用main()方法的執行線程。當調用Thread對象的start()方法時,我們創建了另一個執行線程。在這些start()方法調用之后,我們的程序就有了多個執行線程。當全部的線程執行結束時(更具體點,所有非守護線程結束時),Java程序就結束了。如果初始線程(執行main()方法的主線程)運行結束,其他的線程還是會繼續執行直到執行完成。但是如果某個線程調用System.exit()指示終結程序,那么全部的線程都會結束執行。創建一個Thread類的對象不會創建新的執行線程。同樣,調用實現Runnable接口的run()方法也不會創建一個新的執行線程。只有調用start()方法才能創建一個新的執行線程。
4.特殊建立一個線程代碼如下(常用)
package aliPay;import org.omg.CORBA.PRIVATE_MEMBER;public class troduationalThread {public static void main(String[] args) {// TODO Auto-generated method stubfinal Business business = new Business();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 50; i++) {business.sub(i); }}}).start();for (int i = 0; i < 50; i++) {business.sub(i); business.main(i);}}}class Business{private boolean isShouldSub = true;public synchronized void sub(int i) { while (!isShouldSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch block e.printStackTrace();}}for(int j=1;j<=10;j++){System.out.println("Sub Thread sequence of"+j+"loop of"+i);}isShouldSub = false;this.notify();}public synchronized void main(int i){while (isShouldSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch block e.printStackTrace();}}for(int j=1;j<=10;j++){System.out.println("Main Thread sequence of"+j+"loop of"+i);}isShouldSub = true;this.notify();}}
?