1.多線程之線程狀態
先看一下我網上找到的圖:
Paste_Image.png
- new
線程被創建出來,通過new Thread();就是創建了一個線程,這個時候創建的線程并沒有執行。 - runnable
表示可以執行的,也就是調用了start()方法,調用了start()并不是說線程就運行了,而是需要等操作系統的調度,也就是時間片的輪轉。 - running
這個時候表示線程已經在執行了,也就是獲得了時間片,在運行的過程中可能有一些情況會讓出CPU,線程會進入另外一種狀態。
- 當前線程高風亮節讓出CPU,也就是調用yeild()方法,是當前線程回到runnable狀態。
2)當前線程調用了sleep(),線程進入了wait狀態,也就是圖上所說的blocked();如果線程調用join()也是類似情況
3)當前線程遇到同步代碼塊,或者同步方法(synchronized)線程會進入blocked狀態;如果線程被wait()也也進入blocked狀態。
- blocked
這個時候表示線程被阻塞了,阻塞的情況有很多,可能sleep(),wait(),synchronized等等。 - dead
當前線程執行完了,或者異常退出了。
2.多線程之創建線程
多線程有兩種創建方式:
- implement runnable
//通過實現的方式
static class MyThread1 implements Runnable {
public void run() {
System.out.println("this is implements two method....");
}
}
- extends Thread
//通過繼承的方式
static class MyThread extends Thread {
public void run() {
System.out.println("this is extends thread one method.....");
}
}
Thread 和Runnable區別:
- runnable 比thread靈活,因為Java是單繼承的,但是Java可以實現多個接口。
- runnable可以實現資源共享
例如:
package com.yuxi;
/**
* Created by yuxi on 17/1/26.
*/
public class MyThread {
public static void main(String[] args) {
MyThreadOne myThreadOne1 = new MyThreadOne();
myThreadOne1.start();
MyThreadOne myThreadOne2 = new MyThreadOne();
myThreadOne2.start();
MyThreadOne myThreadOne3 = new MyThreadOne();
myThreadOne3.start();
MyThreadTwo myThreadTwo = new MyThreadTwo();
Thread thread1 = new Thread(myThreadTwo);
Thread thread2 = new Thread(myThreadTwo);
Thread thread3 = new Thread(myThreadTwo);
thread2.start();
thread1.start();
thread3.start();
}
static class MyThreadOne extends Thread {
private int ticket=10;
public void run() {
for (int i = 0; i < 20; i++) {
if (ticket>0) {
System.out.println("當前" + Thread.currentThread().getName() + "買了" + (ticket--) + "票");
}
}
}
}
static class MyThreadTwo implements Runnable {
private int ticket=10;
public void run() {
for (int i = 0; i < 20; i++) {
if (ticket>0) {
System.out.println("當前" + Thread.currentThread().getName() + "買了" + (ticket--) + "票");
}
}
}
}
}
如果是extends結果是:
當前Thread-0買了10票
當前Thread-0買了9票
當前Thread-0買了8票
當前Thread-0買了7票
當前Thread-0買了6票
當前Thread-0買了5票
當前Thread-0買了4票
當前Thread-0買了3票
當前Thread-0買了2票
當前Thread-0買了1票
當前Thread-1買了10票
當前Thread-1買了9票
當前Thread-1買了8票
當前Thread-1買了7票
當前Thread-1買了6票
當前Thread-1買了5票
當前Thread-1買了4票
當前Thread-1買了3票
當前Thread-1買了2票
當前Thread-1買了1票
當前Thread-2買了10票
當前Thread-2買了9票
當前Thread-2買了8票
當前Thread-2買了7票
當前Thread-2買了6票
當前Thread-2買了5票
當前Thread-2買了4票
當前Thread-2買了3票
當前Thread-2買了2票
當前Thread-2買了1票
如果是implement結果是:
當前Thread-1買了10票
當前Thread-0買了9票
當前Thread-1買了8票
當前Thread-0買了7票
當前Thread-0買了5票
當前Thread-1買了6票
當前Thread-1買了3票
當前Thread-1買了2票
當前Thread-0買了4票
當前Thread-2買了1票
原因是因為:
MyThreadTwo myThreadTwo = new MyThreadTwo();
這個對于啟動的三個線程是共享的,他的成員變量 private int ticket=10;是公共資源存在競爭。
MyThreadOne myThreadOne1 = new MyThreadOne();
MyThreadOne myThreadOne2 = new MyThreadOne();
MyThreadOne myThreadOne3 = new MyThreadOne();
分別啟動了三個,這三個之間是不存在競爭的。