A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 指尖的舞者 中级黑马   /  2019-1-28 17:02  /  949 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

java多线程的实现方式:
1、继承Thread
[Java] 纯文本查看 复制代码
public Thread(Runnable target) {
 init(null, target, "Thread-" + nextThreadNum(), 0);
 }

2、实现Runable

这是Runable的源码所以Runable需要重写run方法

[Java] 纯文本查看 复制代码
<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包装器来创建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、对于数据库锁,加锁和解锁必须在一个数据库连接里,负责会出现解锁失败的情况。









0 个回复

您需要登录后才可以回帖 登录 | 加入黑马