以下是一个简单的Java多线程编程实例:
public class MultiThreadExample implements Runnable { private String threadName; public MultiThreadExample(String threadName) { this.threadName = threadName; } @Override public void run() { System.out.println("线程 " + threadName + " 正在运行"); try { for (int i = 5; i > 0; i--) { System.out.println("线程 " + threadName + " :" + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("线程 " + threadName + " 被中断"); } System.out.println("线程 " + threadName + " 运行结束"); } public static void main(String[] args) { Thread thread1 = new Thread(new MultiThreadExample("线程1")); Thread thread2 = new Thread(new MultiThreadExample("线程2")); thread1.start(); thread2.start(); } }
在这个例子中,我们创建了一个MultiThreadExample
类实现了Runnable
接口。这个类包含了一个带有线程名称参数的构造函数和一个run
方法。run
方法定义了线程的执行逻辑,输出线程名称和每秒倒计时5次。
在main
方法中,我们创建了两个线程对象,并分别传入不同的线程名称。然后,我们调用start
方法启动线程。
当我们运行这个程序时,会看到两个线程同时开始运行,并且输出各自的倒计时。