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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java使用Executor(执行器)管理线程

發布時間:2025/3/8 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java使用Executor(执行器)管理线程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一.一個實現了Runnable接口的類

class MyThread implements Runnable{private static int num = 0;@Overridepublic void run() {while(true){synchronized(MyThread.class){++num;try{Thread.sleep(500);} catch(Exception e){System.out.println(e.toString());}System.out.println(Thread.currentThread().getName() + " " + num);}}} }

1.?newCachedThreadPool()方法

  CacheThreadPool會為每一個任務創建一個線程。非常常見的情況是,單個的Executor被用來創建和管理系統中的任務。shutdown()方法可以防止新的任務被提交給這個Executor。如果在shutdown()方法之后提交新任務,則會拋出java.util.concurrent.RejectedExecutionException異常。

public class Main{public static void main(String[] args){ExecutorService exes = Executors.newCachedThreadPool();for(int i=0; i<5; ++i)exes.execute(new MyThread());exes.shutdown(); } }

2.FixedThreadPool()方法

  FixedThreadPool使用了優先的線程集來執行所提交的任務。有了它,你就可以一次性預先執行代價高的線程分配。也就是說如果設置的最大線程數量是x,而提交的線程數y,那么(y-x)對應的這些線程要等到前x個線程執行完畢才會執行。

  下面的例子中,線程6一直不會有機會執行。因為run()方法中是 while(true), 可以將while(true)去掉,前5個線程執行完畢后,才會執行第6個線程。

public class Main{public static void main(String[] args){ExecutorService exes = Executors.newFixedThreadPool(5);for(int i=0; i<6; ++i)exes.execute(new MyThread());exes.shutdown(); } }

3.newSingleThreadExecutor()方法

public class Main{public static void main(String[] args){ ExecutorService exes = Executors.newSingleThreadExecutor();for(int i=0; i<5; ++i)exes.execute(new MyThread());exes.shutdown(); }

  SingleThreadExecutor就像是線程數量為1的FixedThreadPool。這對于你希望在另一個線程中連續運行的事物(長期存活的任務)來說,都是很有用的。如果想SingleThreadExecutor提交了多個任務,那么這些任務將排隊,每個任務都會在下一個任務開始之前結束,所有的任務將使用相同的線程。

?

二.一個實現了Callable<E>接口的類(從任務中產生返回值)

class MyThread implements Callable<String>{private static int num = 0;@Overridepublic String call() throws Exception {for(int i=0; i<5; ++i){synchronized(MyThread.class){++num;Thread.sleep(200);System.out.println(Thread.currentThread().getName() + " " + num);}}return Thread.currentThread().getName() + " success!";} }

1.ExecutorService.submit()方法

public class Main{public static void main(String[] args){ExecutorService exes = Executors.newCachedThreadPool();ArrayList<Future<String>> rets = new ArrayList<Future<String>>();for(int i=0; i<5; ++i)rets.add(exes.submit(new MyThread()));for(Future<String> fs : rets){try {System.out.println(fs.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}} }

  submit()會產生Future對象,它用Callable返回結果的特定類型進行了參數化。可以調用Future的isDone()方法來查詢Future是否已經完成。調用Future的get()方法來獲取最終線程的執行結果。另外,Future的get()方法是一個阻塞方法,直到結果準備就緒

?三.線程的優先級

class MyThread implements Runnable{private int priority;public MyThread(){}public MyThread(int priority){this.priority = priority;}private static int num = 0;private volatile double d;@Overridepublic void run() { Thread.currentThread().setPriority(priority);while(true){for(int i=0; i<100000; ++i){d += (Math.PI+Math.E)/(double)i;if(i%1000 == 0)Thread.yield();}synchronized(MyThread.class){++num;try{Thread.sleep(500);} catch(Exception e){System.out.println(e.toString());}System.out.println(Thread.currentThread().getName() + " " + num);}}} }public class Main{public static void main(String[] args){ExecutorService exes = Executors.newCachedThreadPool();for(int i=0; i<5; ++i)exes.execute(new MyThread(Thread.MIN_PRIORITY));exes.execute(new MyThread(Thread.MAX_PRIORITY));exes.shutdown();} }

  volatile變量保證編譯器對循環不進行任何的優化,如果不加入這些運算的話,就不會看到設置線程優先級的效果。數學運算是可以中斷的,向控制臺打印不能被中斷。這里預案算時間足夠的長,因此線程調度機制才來的及介入,交換任務并關注優先級,是的最高優先級被優先選擇。

四.后臺線程

class SimpleDaemons implements Runnable{@Overridepublic void run() {while(true){try{TimeUnit.MILLISECONDS.sleep(200);System.out.println(Thread.currentThread().getName());} catch(InterruptedException e){System.out.println(Thread.currentThread().getName() + " : InterruptException!");e.printStackTrace();}}} }public class Main{public static void main(String[] args) throws InterruptedException{for(int i=0; i<10; ++i){Thread daemon = new Thread(new SimpleDaemons());daemon.setDaemon(true);daemon.start();}System.out.println("All daemons started");TimeUnit.MILLISECONDS.sleep(1000);} }

  所謂后臺線程,是指程序運行的時候在后臺提供一種通用的服務的線程,并且這種線程并不屬于程序中不可或缺的部分。因此,當所有的非后臺線程結束時,程序也就終止了,同時會殺死進程中的所有的后臺線程。反過來說,只要任何非后臺線程還在運行,程序就不會終止。

  通過定制自己的ThreadFactory, 可以定制有Executor創建的線程的屬性(后臺,優先級,名稱)

class DaemonThreadFactory implements ThreadFactory{@Overridepublic Thread newThread(Runnable r) {Thread t = new Thread(r);t.setDaemon(true);return t;} } class DaemonFromFactory implements Runnable{@Overridepublic void run() {try{TimeUnit.MILLISECONDS.sleep(100);System.out.println(Thread.currentThread().getName());} catch (InterruptedException e){e.printStackTrace();}} }public class Main{public static void main(String[] args) throws InterruptedException{ExecutorService exes = Executors.newCachedThreadPool(new DaemonThreadFactory());for(int i=0; i<5; ++i)exes.execute(new DaemonFromFactory());System.out.println("All Daemos Started!");TimeUnit.MILLISECONDS.sleep(1000);} }

?

轉載于:https://www.cnblogs.com/hujunzheng/p/5097470.html

總結

以上是生活随笔為你收集整理的java使用Executor(执行器)管理线程的全部內容,希望文章能夠幫你解決所遇到的問題。

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