Skip to content

如何在Java中使用线程。首先,我知道Java中的线程可以通过继承Thread类或实现Runnable接口来创建。

继承 Thread

我可以从Thread类继承并重写它的运行方法。例如:

java
public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("线程 " + this.getName() + " 输出: " + i);
            try {
                // 模拟一些工作,比如睡眠
                Thread.sleep(500); 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();

        System.out.println("启动线程");
        thread1.start(); // 启动第一个线程
        thread2.start(); // 启动第二个线程

        try {
            Thread.sleep(5000); 
            System.out.println("等待完成...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

实现 Runnable 接口

或者,我可以实现Runnable接口并重写它的run()方法。例如:

java
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("线程 " + Thread.currentThread().getName() + " 输出: " + i);
            try {
                // 模拟一些工作,比如睡眠
                Thread.sleep(500); 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();

        System.out.println("启动线程");
        new Thread(runnable).start(); 

        try {
            Thread.sleep(5000); 
            System.out.println("等待完成...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

使用 ExecutorService 管理线程

为了更好地管理多个线程,我可以使用ExecutorService。例如:

java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorExample {

    public static void main(String[] args) {
        // 创建一个固定大小的线程池,这里设置为2个线程
        ExecutorService executor = Executors.newFixedThreadPool(2);

        System.out.println("提交任务到执行服务");

        for (int i = 0; i < 5; i++) {
            Runnable task = () -> {
                try {
                    Thread.sleep(1000); 
                    System.out.println("完成第 " + ((Thread) Thread.currentThread()).getName() + " 的任务");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            executor.execute(task);
        }

        // 关闭执行服务
        executor.shutdown();

        try {
            if (!executor.awaitTermination(1, java.util.concurrent.TimeUnit.MINUTES)) {
                System.out.println("超时关闭...");
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("执行服务已关闭");
        }
    }
}

总结

  • 继承 Thread:简单直接,但如果有多个线程类可能会导致类层次结构复杂。
  • 实现 Runnable 接口:更灵活,适合需要传递不同任务的情况,并且可以避免多重继承的问题。
  • 使用 ExecutorService:提供了更高级的线程管理功能,如池化线程和更好的资源利用。