创建多线程的4种方式
1.線程是什么?
? ? ? ? 線程被稱為輕量級進程,是程序執(zhí)行的最小單位,它是指在程序執(zhí)行過程中,能夠執(zhí)行代碼的一個執(zhí)行單位。每個程序程序都至少有一個線程,也即是程序本身。
2.線程狀態(tài)
? ? ? ? Java語言定義了5種線程狀態(tài),在任意一個時間點,一個線程只能有且只有其中一個狀態(tài)。,這5種狀態(tài)如下:
(1)新建(New):創(chuàng)建后尚未啟動的線程處于這種狀態(tài)
(2)運行(Runable):Runable包括了操作系統(tǒng)線程狀態(tài)的Running和Ready,也就是處于此狀態(tài)的線程有可能正在執(zhí)行,也有可能正在等待著CPU為它分配執(zhí)行時間。
(3)等待(Wating):處于這種狀態(tài)的線程不會被分配CPU執(zhí)行時間。等待狀態(tài)又分為無限期等待和有限期等待,處于無限期等待的線程需要被其他線程顯示地喚醒,沒有設(shè)置Timeout參數(shù)的Object.wait()、沒有設(shè)置Timeout參數(shù)的Thread.join()方法都會使線程進入無限期等待狀態(tài);有限期等待狀態(tài)無須等待被其他線程顯示地喚醒,在一定時間之后它們會由系統(tǒng)自動喚醒,Thread.sleep()、設(shè)置了Timeout參數(shù)的Object.wait()、設(shè)置了Timeout參數(shù)的Thread.join()方法都會使線程進入有限期等待狀態(tài)。
(4)阻塞(Blocked):線程被阻塞了,“阻塞狀態(tài)”與”等待狀態(tài)“的區(qū)別是:”阻塞狀態(tài)“在等待著獲取到一個排他鎖,這個時間將在另外一個線程放棄這個鎖的時候發(fā)生;而”等待狀態(tài)“則是在等待一段時間或者喚醒動作的發(fā)生。在程序等待進入同步區(qū)域的時候,線程將進入這種狀態(tài)。
(5)結(jié)束(Terminated):已終止線程的線程狀態(tài),線程已經(jīng)結(jié)束執(zhí)行。
下圖是5種狀態(tài)轉(zhuǎn)換圖:
?
? ? ? ? ? ? ? ??
3.線程同步方法
? ? ? ? 線程有4中同步方法,分別為wait()、sleep()、notify()和notifyAll()。
wait():使線程處于一種等待狀態(tài),釋放所持有的對象鎖。
sleep():使一個正在運行的線程處于睡眠狀態(tài),是一個靜態(tài)方法,調(diào)用它時要捕獲InterruptedException異常,不釋放對象鎖。
notify():喚醒一個正在等待狀態(tài)的線程。注意調(diào)用此方法時,并不能確切知道喚醒的是哪一個等待狀態(tài)的線程,是由JVM來決定喚醒哪個線程,不是由線程優(yōu)先級決定的。
notifyAll():喚醒所有等待狀態(tài)的線程,注意并不是給所有喚醒線程一個對象鎖,而是讓它們競爭。
4.創(chuàng)建線程的方式
? ? ? ? 在JDK1.5之前,創(chuàng)建線程就只有兩種方式,即繼承java.lang.Thread類和實現(xiàn)java.lang.Runnable接口;而在JDK1.5以后,增加了兩個創(chuàng)建線程的方式,即實現(xiàn)java.util.concurrent.Callable接口和線程池。下面是這4種方式創(chuàng)建線程的代碼實現(xiàn)。
4.1繼承Thread類
?
//繼承Thread類來創(chuàng)建線程 public class ThreadTest {public static void main(String[] args) {//設(shè)置線程名字Thread.currentThread().setName("main thread");MyThread myThread = new MyThread();myThread.setName("子線程:");//開啟線程 myThread.start();for(int i = 0;i<5;i++){System.out.println(Thread.currentThread().getName() + i);}} }class MyThread extends Thread{//重寫run()方法public void run(){for(int i = 0;i < 10; i++){System.out.println(Thread.currentThread().getName() + i);}} }?
4.2實現(xiàn)Runnable接口
//實現(xiàn)Runnable接口 public class RunnableTest {public static void main(String[] args) {//設(shè)置線程名字Thread.currentThread().setName("main thread:");Thread thread = new Thread(new MyRunnable());thread.setName("子線程:");//開啟線程thread.start();for(int i = 0; i <5;i++){System.out.println(Thread.currentThread().getName() + i);}} }class MyRunnable implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println(Thread.currentThread().getName() + i);}} }4.3實現(xiàn)Callable接口
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; //實現(xiàn)Callable接口 public class CallableTest {public static void main(String[] args) {//執(zhí)行Callable 方式,需要FutureTask 實現(xiàn)實現(xiàn),用于接收運算結(jié)果FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyCallable());new Thread(futureTask).start();//接收線程運算后的結(jié)果try {Integer sum = futureTask.get();System.out.println(sum);} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}} }class MyCallable implements Callable<Integer> {@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i < 100; i++) {sum += i;}return sum;} }?相較于實現(xiàn)Runnable 接口的實現(xiàn),方法可以有返回值,并且拋出異常。
4.4線程池
? ? ? ? 線程池提供了一個線程隊列,隊列中保存著所有等待狀態(tài)的線程。避免了創(chuàng)建與銷毀額外開銷,提交了響應速度。
?
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //線程池實現(xiàn) public class ThreadPoolExecutorTest {public static void main(String[] args) {//創(chuàng)建線程池ExecutorService executorService = Executors.newFixedThreadPool(10);ThreadPool threadPool = new ThreadPool();for(int i =0;i<5;i++){//為線程池分配任務(wù) executorService.submit(threadPool);}//關(guān)閉線程池 executorService.shutdown();} }class ThreadPool implements Runnable {@Overridepublic void run() {for(int i = 0 ;i<10;i++){System.out.println(Thread.currentThread().getName() + ":" + i);}}}?
?
轉(zhuǎn)載于:https://www.cnblogs.com/zhou-test/p/9811771.html
總結(jié)
以上是生活随笔為你收集整理的创建多线程的4种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Lesson 008 —— python
- 下一篇: vue小细节(1)