请实例展示如何在Java中使用多线程?
在Java中,你可以通过实现Runnable接口或者继承Thread类来创建并使用多线程。
以下是使用Runnable接口创建多线程的示例:
public class MultiThreadExample implements Runnable {
private String threadName;
public MultiThreadExample(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
System.out.println("Thread Name: " + threadName);
// 这里可以执行任何耗时的操作
try {
Thread.sleep(5000); // 睡眠5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MultiThreadExample example1 = new MultiThreadExample("Thread 1"));
MultiThreadExample example2 = new MultiThreadExample("Thread 2"));
Thread thread1 = new Thread(example1);
Thread thread2 = new Thread(example2);
// 启动线程
thread1.start();
thread2.start();
// 等待所有线程结束
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们创建了两个实现了Runnable接口的实例,并将它们分别传递给两个新的Thread对象。然后我们启动这两个线程,最后等待它们全部结束后结束程序。
还没有评论,来说两句吧...