JAVA---线程实现的方式

继承Thread类 重写run方法

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("My Thread.");
    }
}

匿名内部类:

Thread t1 = new Thread() {
    @Override
    public void run() {
        System.out.println("Thread t1.");
    }
};
t1.start();

Lambda:

Thread t2 = new Thread(() -> {
    System.out.println("Thread t2.");
});
t2.start();

实现Runnable接口 重写run方法

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("My Runnable.");
    }
}

实现Callable重写call方法,配合FutureTask

class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "My Callable.";
    }
}
​
public static void main(String[] args) throws ExecutionException, InterruptedException {
    MyCallable callable = new MyCallable();
    FutureTask<String> futureTask = new FutureTask<>(callable);
    Thread thread = new Thread(futureTask);
    thread.start();
    System.out.println(futureTask.get());
}

基于线程池构建线程

其实,都是实现Runnable接口。

1、Thread实现Runnable

public
class Thread implements Runnable {

2、FutureTask实现了Runnable,run方法调用callable。

public class FutureTask<V> implements RunnableFuture<V> {
​
public interface RunnableFuture<V> extends Runnable, Future<V> {
    
public void run() {
    if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran)
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
} 

3、线程池创建的Worker也是实现了Runnable。

private final class Worker
    extends AbstractQueuedSynchronizer
    implements Runnable
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻蛋800

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值