(2)创建和启动线程

53 阅读3分钟

在Java中,可以通过继承Thread类或实现Runnable接口来创建和启动线程。以下是两种常见的创建和启动线程的方法:

方法一:继承Thread类

  1. 创建一个继承自Thread类的子类,并重写run()方法,定义线程的任务。
class MyThread extends Thread {
    public void run() {
        // 在这里定义线程的任务
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread 1: " + i);
        }
    }
}
  1. 创建线程对象并调用start()方法来启动线程。
public class Main {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        thread1.start();
    }
}

方法二:实现Runnable接口

  1. 创建一个实现Runnable接口的类,并重写run()方法,定义线程的任务。
class MyRunnable implements Runnable {
    public void run() {
        // 在这里定义线程的任务
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread 2: " + i);
        }
    }
}
  1. 创建线程对象,并将实现了Runnable接口的对象传递给线程对象。
public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread2 = new Thread(myRunnable);
        thread2.start();
    }
}

注意事项:

  • 使用Thread类的方法更简单,但如果一个类已经继承了其他类(Java不支持多重继承),则无法使用这种方法,此时可以选择实现Runnable接口。
  • 无论使用哪种方法,一旦调用了start()方法,线程将在后台运行,并且执行run()方法中的代码。

无论是继承Thread类还是实现Runnable接口,都可以用于创建和启动线程。选择哪种方法取决于项目的需要和设计约束。通常情况下,推荐使用实现Runnable接口的方式,因为它可以更灵活地管理线程,例如可以共享同一个Runnable实例给多个线程。

继续讨论线程的创建和启动,以下是一些关于线程创建和启动的重要注意事项和示例:

1. 使用Lambda表达式创建线程

Java 8引入了Lambda表达式,使线程创建更加简洁。例如,使用Lambda表达式创建并启动一个线程:

public class Main {
    public static void main(String[] args) {
        Runnable runnable = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 3: " + i);
            }
        };

        Thread thread3 = new Thread(runnable);
        thread3.start();
    }
}

2. 后台线程(Daemon Threads)

线程可以分为前台线程和后台线程。当所有前台线程都执行完毕时,程序会结束,而不会等待后台线程。可以使用setDaemon(true)方法将线程设置为后台线程。

public class Main {
    public static void main(String[] args) {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("Daemon Thread is running.");
            }
        });

        // 将线程设置为后台线程
        daemonThread.setDaemon(true);

        daemonThread.start();

        // 主线程结束,程序结束,即使后台线程仍在运行
    }
}

3. 等待线程完成

有时候,需要等待一个线程完成后才能继续执行主线程的任务,可以使用join()方法等待线程完成。

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread4 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 4: " + i);
            }
        });

        thread4.start();
        
        // 等待thread4线程完成
        thread4.join();

        System.out.println("Main Thread: Thread 4 has finished.");
    }
}

4. 线程的命名和优先级

可以为线程设置名称和优先级:

public class Main {
    public static void main(String[] args) {
        Thread namedThread = new Thread(() -> {
            System.out.println("Named Thread is running.");
        });
        
        // 设置线程名称
        namedThread.setName("MyNamedThread");
        
        // 设置线程优先级
        namedThread.setPriority(Thread.MAX_PRIORITY);

        namedThread.start();
    }
}

线程的名称和优先级可以帮助更好地管理和调试多线程程序。

总之,Java多线程编程提供了多种方式来创建和启动线程,选择适合项目需求的方式非常重要。线程的创建和管理涉及到一些复杂的概念,如线程同步、线程间通信和线程安全性等,需要仔细考虑和设计,以确保程序的正确性和稳定性。