以下是一个简单的Java多线程代码示例:

public class MultiThreadExample implements Runnable {
    private String threadName;
    
    MultiThreadExample(String name) {
        threadName = name;
        System.out.println("Creating " + threadName);
    }
    
    public void run() {
        System.out.println("Running " + threadName);
        try {
            for (int i = 4; i > 0; i--) {
                System.out.println("Thread: " + threadName + ", " + i);
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            System.out.println("Thread " + threadName + " interrupted.");
        }
        System.out.println("Thread " + threadName + " exiting.");
    }
    
    public static void main(String args[]) {
        System.out.println("Main thread starting.");
        
        MultiThreadExample mte1 = new MultiThreadExample("Thread-1");
        MultiThreadExample mte2 = new MultiThreadExample("Thread-2");
        MultiThreadExample mte3 = new MultiThreadExample("Thread-3");
        
        Thread t1 = new Thread(mte1);
        Thread t2 = new Thread(mte2);
        Thread t3 = new Thread(mte3);
        
        t1.start();
        t2.start();
        t3.start();
        
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }
        
        System.out.println("Main thread exiting.");
    }
}

这个代码创建了一个名为MultiThreadExample的类,实现了Runnable接口,并在主线程中创建了三个线程。每个线程都会打印一些简单的文本,然后等待50毫秒。在主线程中,我们调用了每个线程的start()方法来启动它们,然后调用了每个线程的join()方法来等待它们完成。最后,主线程打印一条消息并退出。

写一段Java多线程代码

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

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