Java 创建一个线程的方式

Java中创建线程主要有三种方式,分别为继承Thread类、实现Runnable接口、实现Callable接口。

  • 继承Thread类,重写run()方法,调用start()方法启动线程
public class ThreadTest {

    /**
     * 继承Thread类
     */
    public static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("This is child thread");
        }
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  • 实现 Runnable 接口,重写run()方法
public class RunnableTask implements Runnable {
    public void run() {
        System.out.println("Runnable!");
    }

    public static void main(String[] args) {
        RunnableTask task = new RunnableTask();
        new Thread(task).start();
    }
}

上面两种都是没有返回值的,但是如果我们需要获取线程的执行结果,该怎么办呢?

  • 实现Callable接口,重写call()方法,这种方式可以通过FutureTask获取任务执行的返回值
public class CallerTask implements Callable<String> {
    public String call() throws Exception {
        return "Hello,i am running!";
    }

    public static void main(String[] args) {
        //创建异步任务
        FutureTask<String> task=new FutureTask<String>(new CallerTask());
        //启动线程
        new Thread(task).start();
        try {
            //等待执行完成,并获取返回结果
            String result=task.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java创建线程方式有三种:继承Thread类、实现Runnable接口和实现Callable接口。其中,实现Runnable接口和实现Callable接口的方式更为常用,因为Java只支持单继承,而实现接口可以更好地实现代码的复用。 以下是实现Runnable接口创建线程的示例代码: ```java public class MyRunnable implements Runnable { @Override public void run() { System.out.println("创建线程:" + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } } ``` 以下是实现Callable接口创建线程的示例代码: ```java import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class MyCallableTest implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("创建线程:" + Thread.currentThread().getName()); return 2; } } public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Integer> task = new FutureTask<>(new MyCallableTest()); Thread thread = new Thread(task); thread.start(); System.out.println("创建线程的返回结果为:" + task.get()); } } ``` 除了以上三种方式,还可以使用线程池创建线程,这种方式可以更好地管理线程,避免线程数量过多导致系统资源的浪费。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

每周都想吃火锅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值