并发面试题-创建线程有几种方式

在Java中,创建线程主要有以下几种方式:

1、继承Thread

通过继承Thread类来创建线程是最基本的一种方式。你需要创建一个继承自Thread类的子类,并重写其run方法。然后,你可以创建该子类的实例来创建新的线程。最后,通过调用线程实例的start()方法来启动线程。

class MyThread extends Thread {  
    public void run() {  
        System.out.println("线程运行中");  
    }  
}  

public class Test {  
    public static void main(String[] args) {  
        MyThread t = new MyThread();  
        t.start();  
    }  
}

2、实现Runnable接口

实现Runnable接口是另一种创建线程的方式。你需要创建一个实现了Runnable接口的类的实例,该类必须实现run方法。然后,你可以创建Thread类的一个实例,将Runnable实现类的实例作为构造器参数传递给它。最后,通过调用Thread实例的start()方法来启动线程。

class MyRunnable implements Runnable {  
    public void run() {  
        System.out.println("线程运行中");  
    }  
}  

public class Test {  
    public static void main(String[] args) {  
        Thread t = new Thread(new MyRunnable());  
        t.start();  
    }  
}

3、实现Callable接口结合FutureTask

从Java 5开始,Callable接口被引入,它类似于Runnable接口,但Callable可以返回值,并且可以抛出异常。FutureTask类实现了FutureRunnable接口,它可以把Callable转换成Runnable,并且由于FutureTask实现了Future接口,所以我们可以从中获取异步计算的结果。

import java.util.concurrent.*;  

class MyCallable implements Callable<Integer> {  
    public Integer call() throws Exception {  
        return 123;  
    }  
}  

public class Test {  
    public static void main(String[] args) throws ExecutionException, InterruptedException {  
        FutureTask<Integer> task = new FutureTask<>(new MyCallable());  
        new Thread(task).start();  
        System.out.println(task.get()); // 阻塞直到计算完成,并获取结果  
    }  
}

4、使用线程池

import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  

public class Test {  
    public static void main(String[] args) {  
        ExecutorService executor = Executors.newFixedThreadPool(2);  
        executor.submit(new Runnable() {  
            public void run() {  
                System.out.println("线程运行中");  
            }  
        });  
        executor.shutdown(); // 不再提交任务,关闭线程池  
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值