java 新建线程有哪些常见方法

在Java中,新建线程有多种方法。以下是一些常见的方法:继承Thread类:class MyThread extends Thread {public void run() {// 线程执行的代码}}public class Main {public static void main(String[] args) {MyThread myThread = new MyThread();myThr

在Java中,新建线程有多种方法。以下是一些常见的方法:

  1. 继承Thread类:
class MyThread extends Thread {
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start(); // 启动线程
    }
}
  1. 实现Runnable接口:
class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable); // 创建线程
        thread.start(); // 启动线程
    }
}
  1. 使用Callable接口和Future:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyCallable implements Callable<String> {
    public String call() throws Exception {
        // 线程执行的代码,返回值类型为String
        return "Hello, World!";
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        MyCallable myCallable = new MyCallable();
        Future<String> future = executorService.submit(myCallable); // 提交任务
        String result = future.get(); // 获取任务结果
        System.out.println(result); // 输出结果
        executorService.shutdown(); // 关闭线程池
    }
}
  1. 使用Java 8的CompletableFuture:
import java.util.concurrent.CompletableFuture;

class MyCompletableFuture {
    public static CompletableFuture<String> helloWorld() {
        return CompletableFuture.supplyAsync(() -> {
            // 线程执行的代码,返回值类型为String
            return "Hello, World!";
        });
    }
}

public class Main {
    public static void main(String[] args) {
        MyCompletableFuture.helloWorld().thenAccept(result -> {
            System.out.println(result); // 输出结果
        });
    }
}

这些方法都可以用于在Java中创建和启动线程。你可以根据自己的需求和场景选择合适的方法。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1201428.html

(0)
派派
上一篇 2024-11-29
下一篇 2024-11-29

发表回复

登录后才能评论