// Java线程示例代码
// 创建一个简单的线程类,继承自Thread类
class MyThread extends Thread {
public void run() {
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " - " + i);
try {
// 让线程休眠一段时间
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
// 创建并启动多个线程
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // 启动第一个线程
t2.start(); // 启动第二个线程
// 主线程也执行一些任务
for (int i = 0; i < 5; i++) {
System.out.println("Main thread - " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Thread
类,并重写了 run()
方法。run()
方法中包含了线程要执行的任务。run()
方法中的代码。main
方法中,主线程也会执行一些任务,并且与子线程并发运行。通过这个例子,你可以看到多个线程如何并发执行,并且每个线程都有自己独立的执行路径。
下一篇:java queue
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站