日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java并发编程(一)线程的各种创建方式

發布時間:2024/9/21 java 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java并发编程(一)线程的各种创建方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

方法一:繼承Thread類,作為線程對象存在(繼承Thread對象)

public class CreatThreadDemo1 extends Thread{/*** 構造方法: 繼承父類方法的Thread(String name);方法* @param name*/public CreatThreadDemo1(String name){super(name);}@Overridepublic void run() {while (!interrupted()){System.out.println(getName()+"線程執行了...");try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {CreatThreadDemo1 d1 = new CreatThreadDemo1("first");CreatThreadDemo1 d2 = new CreatThreadDemo1("second");d1.start();d2.start();d1.interrupt(); //中斷第一個線程} }

常規方法,不多做介紹了,interrupted方法,是來判斷該線程是否被中斷。(終止線程不允許用stop方法,該方法不會施放占用的資源。所以我們在設計程序的時候,要按照中斷線程的思維去設計,就像上面的代碼一樣)。

讓線程等待的方法
  • Thread.sleep(200); //線程休息2ms
  • Object.wait(); //讓線程進入等待,直到調用Object的notify或者notifyAll時,線程停止休眠

方法二:實現runnable接口,作為線程任務存在

public class CreatThreadDemo2 implements Runnable {@Overridepublic void run() {while (true){System.out.println("線程執行了...");}}public static void main(String[] args) {//將線程任務傳給線程對象Thread thread = new Thread(new CreatThreadDemo2());//啟動線程thread.start();} }

Runnable 只是來修飾線程所執行的任務,它不是一個線程對象。想要啟動Runnable對象,必須將它放到一個線程對象里。

方法三:匿名內部類創建線程對象

public class CreatThreadDemo3 extends Thread{public static void main(String[] args) {//創建無參線程對象new Thread(){@Overridepublic void run() {System.out.println("線程執行了...");}}.start();//創建帶線程任務的線程對象new Thread(new Runnable() {@Overridepublic void run() {System.out.println("線程執行了...");}}).start();//創建帶線程任務并且重寫run方法的線程對象new Thread(new Runnable() {@Overridepublic void run() {System.out.println("runnable run 線程執行了...");}}){@Overridepublic void run() {System.out.println("override run 線程執行了...");}}.start();}}

創建帶線程任務并且重寫run方法的線程對象中,為什么只運行了Thread的run方法。我們看看Thread類的源碼, image.png

,我們可以看到Thread實現了Runnable接口,而Runnable接口里有一個run方法。
所以,我們最終調用的重寫的方法應該是Thread類的run方法。而不是Runnable接口的run方法。

方法四:創建帶返回值的線程

public class CreatThreadDemo4 implements Callable {public static void main(String[] args) throws ExecutionException, InterruptedException {CreatThreadDemo4 demo4 = new CreatThreadDemo4();FutureTask<Integer> task = new FutureTask<Integer>(demo4); //FutureTask最終實現的是runnable接口Thread thread = new Thread(task);thread.start();System.out.println("我可以在這里做點別的業務邏輯...因為FutureTask是提前完成任務");//拿出線程執行的返回值Integer result = task.get();System.out.println("線程中運算的結果為:"+result);}//重寫Callable接口的call方法@Overridepublic Object call() throws Exception {int result = 1;System.out.println("業務邏輯計算中...");Thread.sleep(3000);return result;} }

Callable接口介紹:

public interface Callable<V> {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/V call() throws Exception; }

返回指定泛型的call方法。然后調用FutureTask對象的get方法得道call方法的返回值。

方法五:定時器Timer

public class CreatThreadDemo5 {public static void main(String[] args) {Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {System.out.println("定時器線程執行了...");}},0,1000); //延遲0,周期1s} }

方法六:線程池創建線程

public class CreatThreadDemo6 {public static void main(String[] args) {//創建一個具有10個線程的線程池ExecutorService threadPool = Executors.newFixedThreadPool(10);long threadpoolUseTime = System.currentTimeMillis();for (int i = 0;i<10;i++){threadPool.execute(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"線程執行了...");}});}long threadpoolUseTime1 = System.currentTimeMillis();System.out.println("多線程用時"+(threadpoolUseTime1-threadpoolUseTime));//銷毀線程池threadPool.shutdown();threadpoolUseTime = System.currentTimeMillis();}}

方法七:利用java8新特性 stream 實現并發

lambda表達式不懂的,可以看看我的java8新特性文章:
java8-lambda:https://www.jianshu.com/p/3a08dc78a05f
java8-stream:https://www.jianshu.com/p/ea16d6712a00

public class CreatThreadDemo7 {public static void main(String[] args) {List<Integer> values = Arrays.asList(10,20,30,40);//parallel 平行的,并行的int result = values.parallelStream().mapToInt(p -> p*2).sum();System.out.println(result);//怎么證明它是并發處理呢values.parallelStream().forEach(p-> System.out.println(p));} } 200 40 10 20 30

怎么證明它是并發處理呢,他們并不是按照順序輸出的 。

總結

以上是生活随笔為你收集整理的Java并发编程(一)线程的各种创建方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。