欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

创建线程有哪几种方式?3种

程序员文章站 2022-05-04 08:49:52
1.继承Thread类型重写run 方法public class ThreadDemoTest extends Thread{ @Override public void run() { System.out.println("通过继承Thread类重写run方法实现接口!"); } public static void main(String[] args) { ThreadDemoTest threadDemoTest = new T...

1.继承Thread类型重写run 方法

public class ThreadDemoTest extends Thread{
    @Override
    public void run() {
        System.out.println("通过继承Thread类重写run方法实现接口!");
    }
 
    public static void main(String[] args) {
        ThreadDemoTest threadDemoTest = new ThreadDemoTest();
        threadDemoTest.run();
    }
}

2.实现Runnable接口

public class RunnableDemoTest implements Runnable{
 
    public void run() {
        System.out.println("实现Runnable开启线程!");
    }
 
    public static void main(String[] args) {
        Thread thread = new Thread(new RunnableDemoTest());
        thread.start();
    }
}

3.实现Callable接口

public class CallableDemoTest implements Callable {
    public Object call() {
        return "HelloCallable!";
    }
 
    @Test
    public void test() throws ExecutionException, InterruptedException {
        CallableDemoTest callableDemoTest = new CallableDemoTest();
        FutureTask futureTask = new FutureTask(callableDemoTest);
        Thread thread = new Thread(futureTask);
        thread.start();
        //获取返回值
        futureTask.get();
    }
}

本文地址:https://blog.csdn.net/sinat_41920065/article/details/107455667