如何在Java中使用多线程实例
在Java中,我们可以使用Thread类来创建和运行多线程。以下是一个简单的多线程实例:
// 创建一个线程类
public class MyThread extends Thread {
// 定义要在线程中执行的代码
private String task;
// 构造函数,传入任务内容
public MyThread(String task) {
this.task = task;
}
// 实现run方法,这里是线程的主要执行部分
@Override
public void run() {
System.out.println("Task started: " + task);
// 这里是你要在线程中执行的代码,例如模拟IO操作
try {
Thread.sleep(2000); // 模拟耗时操作,这里设置为2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task completed: " + task);
}
}
// 创建线程并启动
public class Main {
public static void main(String[] args) {
// 创建线程实例,传入任务内容
MyThread thread1 = new MyThread("Task 1"));
MyThread thread2 = new MyThread("Task 2");
// 启动线程
thread1.start();
thread2.start();
}
}
在这个例子中,我们创建了两个线程(thread1和thread2),每个线程都有一个特定的任务。当主线程调用start方法启动线程时,这些任务将在各自的线程上并发执行。
还没有评论,来说两句吧...