java多線程的實(shí)現(xiàn)方式:
1、繼承Thread
[Java] 純文本查看 復(fù)制代碼
1
2
3
|
public Thread(Runnable target) {
init( null , target, "Thread-" + nextThreadNum(), 0 );
}
|
2、實(shí)現(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= """ ><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
|
特點(diǎn):可以返回值
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、避免一個(gè)線程同時(shí)獲取多個(gè)鎖2、避免一個(gè)線程在鎖內(nèi)同時(shí)占用多個(gè)資源3、嘗試使用定時(shí)鎖,使用lock.tryLock(timeout)來替代使用內(nèi)部鎖機(jī)制。4、對(duì)于數(shù)據(jù)庫鎖,加鎖和解鎖必須在一個(gè)數(shù)據(jù)庫連接里,負(fù)責(zé)會(huì)出現(xiàn)解鎖失敗的情況。 |