java多線程的實現(xiàn)方式:
1、繼承Thread
[Java] 純文本查看 復制代碼
1
2
3
|
public Thread(Runnable target) {
init( null , target, "Thread-" + nextThreadNum(), 0 );
}
|
2、實現(xiàn)Runable
這是Runable的源碼所以Runable需要重寫run方法
[Java] 純文本查看 復制代碼
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
<font style= "color:rgb(79, 79, 79)" ><font face= """ ><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] 純文本查看 復制代碼
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;
}
|
死鎖問題:
避免死鎖的幾種常見方法:1、避免一個線程同時獲取多個鎖2、避免一個線程在鎖內同時占用多個資源3、嘗試使用定時鎖,使用lock.tryLock(timeout)來替代使用內部鎖機制。4、對于數(shù)據(jù)庫鎖,加鎖和解鎖必須在一個數(shù)據(jù)庫連接里,負責會出現(xiàn)解鎖失敗的情況。 |