java中多线程实际案例
时间: 2024-04-08 19:27:42 浏览: 64
以下是一个Java中的多线程实际案例[^1][^2]:
```java
public class ThreadExample extends Thread {
private String threadName;
public ThreadExample(String name) {
threadName = name;
}
public void run() {
System.out.println("Thread " + threadName + " is running.");
try {
for (int i = 5; i > 0; i--) {
System.out.println("Thread " + threadName + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public static void main(String[] args) {
ThreadExample thread1 = new ThreadExample("Thread 1");
ThreadExample thread2 = new ThreadExample("Thread 2");
thread1.start();
thread2.start();
}
}
```
这个案例中,我们创建了一个继承自Thread类的ThreadExample类。在run()方法中,我们定义了线程的具体逻辑。在main()方法中,我们创建了两个ThreadExample对象,并通过调用start()方法来启动线程。
运行这个程序,你将会看到两个线程同时运行,每个线程都会倒数输出数字,并在每个数字之间暂停1秒。这个案例展示了Java中多线程的基本用法和实际应用。
阅读全文