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

歡迎訪問 生活随笔!

生活随笔

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

java

Java多线程的几种写法

發(fā)布時間:2023/12/31 java 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java多线程的几种写法 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Java多線程的在開發(fā)中用到的很多,簡單總結一下幾種寫法,分別是繼承Thread方法,實現(xiàn)Runnable接口,實現(xiàn)Callable接口;
1.繼承Thread方法

class TestThread extends Thread{String name;public TestThread(String name){this.name=name;}@Overridepublic void run() {for (int i = 0; i < 6; i++) {System.out.println(this.name+":"+i);}} }

main方法調(diào)用:
Thread啟動有兩個方法,一個是start()方法,一個是run()方法,但是直接調(diào)用run方法時線程不會交替運行,而是順序執(zhí)行,只有用start方法時才會交替執(zhí)行

TestThread tt1 = new TestThread("A");TestThread tt2 = new TestThread("B");tt1.start();tt2.start();

運行結果:

2.實現(xiàn)Runnable接口,有多種寫法
2.1外部類

class TestRunnable implements Runnable{String name;public TestRunnable(String name){this.name=name;}@Overridepublic void run() {for (int i = 0; i < 6; i++) {System.out.println(this.name+":"+i);}} }

調(diào)用:

TestRunnable tr1 = new TestRunnable("C");TestRunnable tr2 = new TestRunnable("D");new Thread(tr1).start();new Thread(tr2).start();

2.2匿名內(nèi)部類方式

new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stub}}).start();

2.3 Lamda表達式,jdk1.8,只要是函數(shù)式接口,都可以使用Lamda表達式或者方法引用

new Thread(()->{for (int i = 0; i < 6; i++) {System.out.println(i);}}).start();

2.4ExecutorService創(chuàng)建線程池的方式

class TestExecutorService implements Runnable{ String name; public TestExecutorService(String name){this.name=name; }@Overridepublic void run() {for (int i = 0; i < 6; i++) {System.out.println(this.name+":"+i);}} }

調(diào)用:可以創(chuàng)建固定個數(shù)的線程池

ExecutorService pool = Executors.newFixedThreadPool(2);TestExecutorService tes1 = new TestExecutorService("E");TestExecutorService tes2 = new TestExecutorService("F");pool.execute(tes1);pool.execute(tes2);pool.shutdown(); 運行結果跟2.1差不多

3.實現(xiàn)Callable接口,可以返回結果

//Callable<V>提供返回數(shù)據(jù),根據(jù)需要返回不同類型 class TestCallable implements Callable<String>{private int ticket = 5;@Overridepublic String call() throws Exception {for (int i = 0; i < 5; i++) {if(this.ticket>0)System.out.println("買票,ticket="+this.ticket--);}return "票賣完了";} }

調(diào)用:

Callable<String> tc = new TestCallable();FutureTask<String> task = new FutureTask<String>(tc);new Thread(task).start();try {System.out.println(task.get());//獲取返回值} catch (InterruptedException | ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();} 運行結果:

轉(zhuǎn)載于:https://blog.51cto.com/10553553/2065549

總結

以上是生活随笔為你收集整理的Java多线程的几种写法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。