1.通过继承Thread类:
- public class MyThread extends Thread {
- public void run() {
- // 线程执行的任务
- System.out.println("线程执行任务");
- }
-
- public static void main(String[] args) {
- MyThread myThread = new MyThread();
- myThread.start(); // 启动线程
- }
- }
2.通过实现Runnable接口:
- public class MyRunnable implements Runnable {
- public void run() {
- // 线程执行的任务
- System.out.println("线程执行任务");
- }
-
- public static void main(String[] args) {
- MyRunnable myRunnable = new MyRunnable();
- Thread thread = new Thread(myRunnable);
- thread.start(); // 启动线程
- }
- }
3.使用Lambda表达式来创建线程:
- public class Main {
- public static void main(String[] args) {
- // 使用Lambda表达式创建线程
- Thread thread = new Thread(() -> {
- // 线程执行的任务
- System.out.println("线程执行任务");
- });
- thread.start(); // 启动线程
- }
- }
- public class MyRunnable implements Runnable {
- @Override
- public void run() {
- // 定义具体的任务逻辑
- System.out.println("Executing my task...");
- }
- }
-
- public class Main {
- public static void main(String[] args) {
- // 创建Runnable实例
- Runnable myRunnable = new MyRunnable();
-
- // 创建Thread实例并将任务分配给线程
- Thread thread = new Thread(myRunnable);
-
- // 启动线程
- thread.start();
- }
- }
start() 方法:
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- System.out.println("\"qd0\" = " + "qd0");
- }
- });
- thread.start();
run() 方法:
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- System.out.println("\"qd0\" = " + "qd0");
- }
- });
- thread.run();
总结来说,start() 方法用于启动一个新的线程,并由 JVM 调用新线程的 run() 方法;而 run() 方法则是线程的实际执行体,如果直接调用该方法,将在当前线程中同步执行,不会启动新线程。