java实现多线程的方式有哪几种

39次阅读
没有评论

共计 1643 个字符,预计需要花费 5 分钟才能阅读完成。

Java 实现多线程的方式有以下几种:

  1. 继承 Thread 类:创建一个类,继承自 Thread 类,并重写 run() 方法,在 run() 方法中定义线程要执行的任务。然后创建该类的对象,并调用 start() 方法启动线程。
class MyThread extends Thread {public void run() {// 线程要执行的任务 
    }
}

public class Main {public static void main(String[] args) {MyThread thread = new MyThread();
        thread.start();}
}
  1. 实现 Runnable 接口:创建一个类,实现 Runnable 接口,并重写 run() 方法,在 run() 方法中定义线程要执行的任务。然后创建该类的对象,并将其作为参数传递给 Thread 类的构造函数,最后调用 start() 方法启动线程。
class MyRunnable implements Runnable {public void run() {// 线程要执行的任务 
    }
}

public class Main {public static void main(String[] args) {MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();}
}
  1. 使用 Callable 和 Future 接口:创建一个类,实现 Callable 接口,并重写 call() 方法,在 call() 方法中定义线程要执行的任务。然后创建该类的对象,并将其作为参数传递给 ExecutorService 的 submit() 方法,通过 Future 对象可以获取线程的执行结果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyCallable implements Callable<String> {public String call() {// 线程要执行的任务 
        return " 任务执行结果 ";
    }
}

public class Main {public static void main(String[] args) throws Exception {MyCallable callable = new MyCallable();
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(callable);
        String result = future.get();
        System.out.println(result);
        executorService.shutdown();}
}
  1. 使用线程池:通过 Executor 框架提供的线程池来管理线程的创建和执行。可以使用 Executors 类提供的静态方法创建不同类型的线程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {executorService.execute(new Runnable() {public void run() {// 线程要执行的任务 
                }
            });
        }
        executorService.shutdown();}
}

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-01-29发表,共计1643字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)