多线程学习总结(线程的创建)

线程创建的三种方式

1.继承Thread类
public class Test07 {
    public static void main(String[] args) {
        new MyThread().start();
    }
}
class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        System.out.println("11111");
    }
}
2.实现Runnable接口

public class Test08 {
    public static void main(String[] args) {
        new Thread(new MyThread2()).start();
    }
}
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("22222");
    }
}
3.实现Callable接口

在这里插入图片描述

1.Thread()参数要放一个Runnable的一个实现类
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}
2.RunnableFuture接口继承了Runnable接口
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
3.FutureTask实现了上边那个接口,而且它里边的构造方法可以传Callable
public class FutureTask<V> implements RunnableFuture<V> {
public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}
}
具体操作如下
public class Test09 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread3 myThread3 = new MyThread3();
        FutureTask<String> task = new FutureTask<>(myThread3);
        new Thread(task).start();
        String s = task.get();
        System.out.println(s);
    }
}
class MyThread3 implements Callable<String>{

    @Override
    public String call() throws Exception {
        return "3333";
    }
}
Callable 这里的泛型就是方法的返回类型,通过task.get()方法可以获得。而Runnable接口,没有返回类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值