Java并发学习之一——线程的创建
與每個(gè)java語(yǔ)言中的元素一樣,線程是對(duì)象。在Java中,我們有兩種方式創(chuàng)建線程:
1、通過(guò)直接繼承thread類,然后覆蓋run方法。
2、構(gòu)建一個(gè)實(shí)現(xiàn)Runnable接口的類,然后創(chuàng)建一個(gè)thread類對(duì)象并傳遞Runnable對(duì)象作為構(gòu)造參數(shù)
代碼如下:
public class Calculator implements Runnable{ private int number; public Calculator(int number){ this.number = number; } /** * run()方法是創(chuàng)建的線程執(zhí)行指令 */ @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、每個(gè)Java程序最少有一個(gè)執(zhí)行線程。當(dāng)你運(yùn)行程序的時(shí)候,JVM運(yùn)行負(fù)責(zé)調(diào)用main()方法的執(zhí)行線程。當(dāng)調(diào)用Thread對(duì)象的start()方法時(shí),我們創(chuàng)建了另一個(gè)執(zhí)行線程。在這些start()方法調(diào)用之后,我們的程序就有了多個(gè)執(zhí)行線程。當(dāng)全部的線程執(zhí)行結(jié)束時(shí)(更具體點(diǎn),所有非守護(hù)線程結(jié)束時(shí)),Java程序就結(jié)束了。如果初始線程(執(zhí)行main()方法的主線程)運(yùn)行結(jié)束,其他的線程還是會(huì)繼續(xù)執(zhí)行直到執(zhí)行完成。但是如果某個(gè)線程調(diào)用System.exit()指示終結(jié)程序,那么全部的線程都會(huì)結(jié)束執(zhí)行。創(chuàng)建一個(gè)Thread類的對(duì)象不會(huì)創(chuàng)建新的執(zhí)行線程。同樣,調(diào)用實(shí)現(xiàn)Runnable接口的run()方法也不會(huì)創(chuàng)建一個(gè)新的執(zhí)行線程。只有調(diào)用start()方法才能創(chuàng)建一個(gè)新的執(zhí)行線程。
4.特殊建立一個(gè)線程代碼如下(常用)
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();}}?
轉(zhuǎn)載于:https://www.cnblogs.com/pypua/articles/7233929.html
總結(jié)
以上是生活随笔為你收集整理的Java并发学习之一——线程的创建的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 申请中信银行国航携程联名信用卡有什么条件
- 下一篇: Java IO(二)——RandomAc