Java多线程的几种写法
生活随笔
收集整理的這篇文章主要介紹了
Java多线程的几种写法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Java多線程的在開發(fā)中用到的很多,簡單總結一下幾種寫法,分別是繼承Thread方法,實現(xiàn)Runnable接口,實現(xiàn)Callable接口;
1.繼承Thread方法
main方法調(diào)用:
Thread啟動有兩個方法,一個是start()方法,一個是run()方法,但是直接調(diào)用run方法時線程不會交替運行,而是順序執(zhí)行,只有用start方法時才會交替執(zhí)行
運行結果:
2.實現(xiàn)Runnable接口,有多種寫法
2.1外部類
調(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: svn备份遇到的问题
- 下一篇: java美元兑换,(Java实现) 美元