我先寫個提綱,分為這幾個模組來講:
1,java中線程的建立的兩種方法
2,兩種方法的實質性區別和使用區別
3,線程的狀態
4,synchronized上鎖機制
5,線程之間的同步
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1,java中線程的建立的兩種方法
java中想要實現線程有兩種方法,一種是繼承Thread類,一種是實現Runnable介面.這兩種方法的本質是一樣的.只是設計模式有所區別.
先來看看第一種方法:繼承Thread類.
class DemoThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("Demo Thread running!");
}
}
public class MyThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
DemoThread demoThread = new DemoThread();
demoThread.start();
}
}
DemoThread繼承了Thread這個類,這就意味這DemoThread現在是一個線程類,可以用來作為一個線程啟動(調用Thread類Start()方法).然後啟動後會執行run()裡面代碼.
再說說Runnable介面的實現:Runnable的源碼
public interface Runnable {
public abstract void run();
}
下面看下實現的代碼
class DemoRunnable implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Demo Thread running!");
}
}
public class MyThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
DemoRunnable demoRunnable = new DemoRunnable();
Thread thread = new Thread(demoRunnable);
thread.start();
}
}
其實要實現一個線程還是需要一個Thread的對象,然後在建構函式中傳入實現Runnable介面類的對象,同樣調用start()方法開啟線程.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2,兩種方法的實質性區別和使用區別
我們要研究這兩種實現線程方法的實質性區別就得看java的原始碼了.下面我簡單講講這兩種方法的實質性區別.
我們首先要知道,調用start()方法後系統會開始把線程的狀態置為runnable的狀態(待會會講到線程狀態),然後等系統時間片輪到該線程的時候就會執行run()方法,所以我們要去 比
較2種方法的區別就得關注兩點,第一點是各自的建構函式的區別,第二點就是run方法的區別.
先看第一點,第一種DemoThread demoThread = new DemoThread();因為子類沒有重寫建構函式,所以這種建構函式實質是調用了父類的構造方法.看Thread構造方法原始碼:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
第二種Thread thread = new Thread(demoRunnable);
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
然後看看init()方法
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
this.name = name.toCharArray();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext = AccessController.getContext();
this.target = target;
setPriority(priority);
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
大家請看紅色部分,其實Thread()建構函式調用的init()方法然後Runnable targetc傳給了Thread的成員變數。接下來看看Thread中的run()方法
如果我們用的是第一種實現線程的方式它在執行run()的時候target 是為空白的所以它直接就會去執行子類重寫的run()方法,而第二種target其實是傳入實現Runnable介面的類的對象,那麼執行的就是Runnable介面的類的對象run()方法了.
那麼現在我們最關心的問題是這兩種方法在何種情況下使用何種方法?在java中類是單繼承的,當一個類有父類的時候我們還想讓它作為線程去跑那就去實現runnable介面,如果沒有父類就可以繼承Thread類了.不過我建議盡量使用實現runnable介面的方法,所不定你那天代碼需要重構,會對線程類抽象出一個父類也不一定.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3,線程的狀態
線程的狀態:
當我們new出一個Thread後並調用start()那麼該Thread就是runnable狀態,這個時候系統會為每個Thread分配時間片,如果時間片輪到了該 Thread那麼就會進入running狀態,當running當時間片過了會又回到runnable狀態,如此反覆,直到Thread運行結束進入dead狀態.這裡有個線程等待狀態需要特別說明一下,這是為了讓線程同步的一種狀態.在下麵線程同步模組會提到
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4,synchronized上鎖機制
現在有兩個旅遊團AB同時要去唐寅園參觀,但是唐寅園只能容納一個旅遊團,這個時候就需要旅遊團去向唐寅園景區的負責人預約,但是唐寅園的負責人不止1個,那A向負責人預約的時候同時也有可能B也向另外一個負責人預約了.我們可以把AB旅遊團預約看成A線程和B線程,唐寅園景區可以看成一個對象,那向負責人預約的這個過程可以作為該對象的一個方法.那麼就會出現A,B線程同時訪問同一個對象的同一個方法.但是有些時候我們是不允許多個線程訪問同一資源這種情況.所以需要為資源加鎖以防止多個線程同時訪問.在java中為每個對象都提供了鎖機制,用來防止多個線程同時訪問該對象的資源.我們可以用synchronized關鍵字來為對象中不允許多線程同時訪問的成員變數和成員方法加鎖.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
5,線程之間的同步
還是兩個旅遊團AB的例子,這裡由於負責人與旅遊團A的關係好,他希望旅遊團A先去參觀唐寅園,那麼現在就會出現AB同時預約但是,負責人讓A先預約成功,如果先接到B的預約電話,那麼負責人必須要他等待A預約後.
在java中實現同步方法是wait()和notify(),這兩個方法必須在對象加鎖的方法(也就是加了synchronized關鍵字的方法)才能調用.
wait()掛載該線程
notify()通知一個掛載的線程使其執行
最後發個剛才例子的demo
//旅行團A
class TouringPartA implements Runnable{
private Principal principal;
public TouringPartA(Principal principal){
this.principal = principal;
}
@Override
public void run() {
// TODO Auto-generated method stub
principal.makeappointment(this);
}
}
//旅行團B
class TouringPartB implements Runnable{
private Principal principal;
public TouringPartB(Principal principal){
this.principal = principal;
}
@Override
public void run() {
// TODO Auto-generated method stub
principal.makeappointment(this);
}
}
//負責人
class Principal{
//判斷旅遊團A是否已經預約
private boolean isAmakeappointment = false;
public synchronized void makeappointment(Runnable thread){
if(thread instanceof TouringPartB){
if(!isAmakeappointment){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("旅遊團 B 預約成功!");
}
else{
System.out.println("旅遊團 A 預約成功!");
isAmakeappointment = true;
notify();
}
}
}
public class Journey {
public static void main(String[] args) {
// TODO Auto-generated method stub
Principal principal = new Principal();
TouringPartA touringPartA = new TouringPartA(principal);
TouringPartB touringPartB = new TouringPartB(principal);
Thread t1 = new Thread(touringPartA);
Thread t2 = new Thread(touringPartB);
t1.start();
t2.start();
}
}