Java 创建主线程和子线程:详细教程与代码示例
要创建主线程和子线程,可以使用 Java 中的 Thread 类来实现。
创建主线程: 主线程是程序的入口,在 Java 中,主线程是由 JVM 自动创建的。可以通过编写 main 方法来定义主线程的执行逻辑。
public class MainThread {
public static void main(String[] args) {
// 主线程的执行逻辑
System.out.println('This is the main thread.');
}
}
创建子线程: 创建子线程有两种方式,一种是继承 Thread 类,另一种是实现 Runnable 接口。
- 继承 Thread 类:
public class MyThread extends Thread {
@Override
public void run() {
// 子线程的执行逻辑
System.out.println('This is a child thread.');
}
}
public class MainThread {
public static void main(String[] args) {
// 创建子线程对象
MyThread myThread = new MyThread();
// 启动子线程
myThread.start();
// 主线程的执行逻辑
System.out.println('This is the main thread.');
}
}
- 实现 Runnable 接口:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 子线程的执行逻辑
System.out.println('This is a child thread.');
}
}
public class MainThread {
public static void main(String[] args) {
// 创建子线程对象
MyRunnable myRunnable = new MyRunnable();
// 创建 Thread 对象,并将 Runnable 对象作为参数传入
Thread myThread = new Thread(myRunnable);
// 启动子线程
myThread.start();
// 主线程的执行逻辑
System.out.println('This is the main thread.');
}
}
无论是继承 Thread 类还是实现 Runnable 接口,都需要重写 run 方法,在 run 方法中编写子线程的执行逻辑。调用 start 方法来启动子线程,JVM 会自动调用 run 方法来执行子线程的逻辑。
原文地址: https://www.cveoy.top/t/topic/qbKK 著作权归作者所有。请勿转载和采集!