java多线程的实现方式:
1、继承Thread
[Java] 纯文本查看 复制代码 public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
} 2、实现Runable
这是Runable的源码所以Runable需要重写run方法 [Java] 纯文本查看 复制代码 @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();
}
3、接口通过FutureTask包装器来创建Thread线程
[Java] 纯文本查看 复制代码 特点:可以返回值
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、避免一个线程在锁内同时占用多个资源3、尝试使用定时锁,使用lock.tryLock(timeout)来替代使用内部锁机制。4、对于数据库锁,加锁和解锁必须在一个数据库连接里,负责会出现解锁失败的情况。
|