请展示一个Java多线程的例子。
在Java中,我们可以使用Thread类来创建和管理多线程。以下是一个简单的例子,展示了如何创建两个线程并发执行任务:
// 创建线程类
public class MyThread extends Thread {
// 线程启动时调用的方法
public void run() {
System.out.println("Thread " + this.getName() + " is running.");
// 这里是你的多线程任务,可以替换为你需要执行的代码
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread " + this.getName() + " is finished.");
}
// 创建线程的构造函数,需要传入线程名称
public MyThread(String name) {
super(name);
}
}
// 主程序
public class MultiThreadExample {
public static void main(String[] args) {
// 创建两个线程对象
MyThread thread1 = new MyThread("Thread 1"));
MyThread thread2 = new MyThread("Thread 2"));
// 启动线程
thread1.start();
thread2.start();
try {
// 等待所有线程执行完毕
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads have finished.");
}
}
在这个例子中,我们创建了两个线程thread1
和thread2
。每个线程都在run()
方法中执行特定的任务。
主程序使用start()
方法启动线程,并通过join()
方法等待所有线程执行完毕。最后,打印一条消息表示所有线程已经完成任务。
还没有评论,来说两句吧...