以下是一个简单的 Java 多线程示例,演示如何使用 Runnable 接口创建和启动线程:

public class MultiThreadExample implements Runnable {

    private String threadName;

    public MultiThreadExample(String threadName) {
        this.threadName = threadName;
    } 

    @Override
    public void run() {
        System.out.println('Thread ' + threadName + ' is running.');
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println('Thread ' + threadName + ' is finished.');
    }

    public static void main(String[] args) {
        MultiThreadExample t1 = new MultiThreadExample('Thread 1');
        MultiThreadExample t2 = new MultiThreadExample('Thread 2');

        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);

        thread1.start();
        thread2.start();
    }
}

在这个示例中,我们创建了一个名为 MultiThreadExample 的类,它实现了 Runnable 接口。然后,我们在 MultiThreadExample 类中实现了 run() 方法,该方法包含了线程要执行的代码。在 main() 方法中,我们创建了两个 MultiThreadExample 对象,并将它们放入两个 Thread 对象中。最后,我们启动了这两个线程。

当我们运行这个程序时,输出如下:

Thread Thread 1 is running.
Thread Thread 2 is running.
Thread Thread 1 is finished.
Thread Thread 2 is finished.

可以看到,两个线程是同时运行的,它们在不同的时间完成了它们的任务。这就是多线程的好处:它可以让我们的程序更加高效和灵活。

Java 多线程示例:实现并行任务执行

原文地址: https://www.cveoy.top/t/topic/lvXo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录