java多线程的实现方式:
1、继承Thread
[Java] 纯文本查看 复制代码
1
2
3
|
public Thread(Runnable target) {
init( null , target, "Thread-" + nextThreadNum(), 0 );
}
|
2、实现Runable
这是Runable的源码所以Runable需要重写run方法
[Java] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
"color:rgb(79, 79, 79)" >""" >"font-size:16px" > @FunctionalInterface [/size][/font][/color][/p] public interface Runnable {
/**
* When an object implementing interface Runnable is used
* to create a thread, starting the thread causes the object's
* run method to be called in that separately executing
* thread.
* The general contract of the method run is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
|
3、接口通过FutureTask包装器来创建Thread线程
[Java] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
|
特点:可以返回值
public class FutureTask implements RunnableFuture
public interface RunnableFuture extends Runnable, Future {
使用Callable方式,需要Futertask的支持
public FutureTask(Callable callable) {
if (callable == null )
throw new NullPointerException();
this .callable = callable;
this .state = NEW;
}
|
死锁问题:
避免死锁的几种常见方法:1、避免一个线程同时获取多个锁2、避免一个线程在锁内同时占用多个资源3、尝试使用定时锁,使用lock.tryLock(timeout)来替代使用内部锁机制。4、对于数据库锁,加锁和解锁必须在一个数据库连接里,负责会出现解锁失败的情况。 |