教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

java多線程

更新時間:2019年01月10日15時01分 來源:傳智播客 瀏覽次數(shù):

java多線程的實現(xiàn)方式:
1、繼承Thread
[Java] 純文本查看 復(fù)制代碼
1
2
3
public Thread(Runnable target) {
 init(null, target, "Thread-" + nextThreadNum(), 0);
 }
2、實現(xiàn)Runable

這是Runable的源碼所以Runable需要重寫run方法

[Java] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
<font style="color:rgb(79, 79, 79)"><font face="&quot"><font style="font-size:16px">@FunctionalInterface[/size][/font][/color][/p]public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
</font></font></font>
3、接口通過FutureTask包裝器來創(chuàng)建Thread線程
[Java] 純文本查看 復(fù)制代碼
01
02
03
04
05
06
07
08
09
10
11
12
特點:可以返回值
 
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {
使用Callable方式,需要Futertask的支持
 
    public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}

死鎖問題:
避免死鎖的幾種常見方法:1、避免一個線程同時獲取多個鎖2、避免一個線程在鎖內(nèi)同時占用多個資源3、嘗試使用定時鎖,使用lock.tryLock(timeout)來替代使用內(nèi)部鎖機制。4、對于數(shù)據(jù)庫鎖,加鎖和解鎖必須在一個數(shù)據(jù)庫連接里,負(fù)責(zé)會出現(xiàn)解鎖失敗的情況。



作者:傳智播客JavaEE培訓(xùn)學(xué)院

首發(fā):http://java.itcast.cn

0 分享到:
和我們在線交談!