深入解析Java多线程:探究不同的实现方法,需要具体代码示例
摘要:Java作为一种广泛使用的编程语言,提供了丰富的多线程支持。本文将深入探讨Java多线程的实现方法,包括继承Thread类、实现Runnable接口以及使用线程池。通过具体的代码示例,读者将能够更好地理解和运用这些方法。
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread 1: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main thread: " + i);
}
}
}
登录后复制
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread 2: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread2 = new Thread(myRunnable);
thread2.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main thread: " + i);
}
}
}
登录后复制
public class MyTask implements Runnable {
private int taskId;
public MyTask(int taskId) {
this.taskId = taskId;
}
@Override
public void run() {
System.out.println("Task " + taskId + " is running.");
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
MyTask task = new MyTask(i);
executorService.execute(task);
}
executorService.shutdown();
}
}
登录后复制
参考文献:
- Oracle. (n.d.). The Java™ Tutorials - Lesson: Concurrency. Oracle. Retrieved from https://docs.oracle.com/javase/tutorial/essential/concurrency/
以上就是深入解析Java多线程:探究不同的实现方法的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!