0
点赞
收藏
分享

微信扫一扫

Java--多线程(创建线程的主要方式)

霸姨 2022-02-14 阅读 90

1 创建线程的方式

2 线程的创建说明

3 对比创建线程的三种方式

4 实例代码

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class TestMyThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    //  通过继承Thread类,创建Thread的对象,启动线程
        new Mythread01().start();
    /*
        通过创建Runnable实现类的实例,
        此实例作为Thread的target来创建Thread对象,
        调用线程对象的start()方法来启动该线程。
     */
        new Thread(new Mythread02()).start();
    //        创建Thread对象并将FutureTask对象作为参数传递Thread的构造器中。
        FutureTask<Integer> futuretask = new FutureTask<Integer>(new Mythreadd03());
    //        调用Thread启动的start()方法
        new Thread(futuretask).start();
    //        获取返回值
        System.out.println(futuretask.get());
    }
}

//继承Thread类
class Mythread01 extends Thread{
//    重写run方法
    public void run(){
        System.out.println("继承Thread类");
    }
}

//实现Runnable接口
class Mythread02 implements Runnable{
//    重写run方法
    @Override
    public void run() {
        System.out.println("实现Runnable接口");
    }
}

//实现Callable
class Mythreadd03 implements Callable<Integer>{ 
//    重写call方法
    @Override
    public Integer call() throws Exception {
        System.out.println("实现Callable接口");
        return 1;
    }
}

5 效果展示

举报

相关推荐

0 条评论