新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

Java中的Thread.join()怎样使用,java中的threadPool怎样导入

发布时间:2023-08-14 08:33:09

Java中的Thread.join()怎样使用

Thread.join()方法用于等待一个线程履行完成。它可以在一个线程中调用另外一个线程的join()方法,使得当前线程等待被调用线程履行完成后再继续履行。
以下是Thread.join()方法的使用示例:
```java
public class ThreadJoinExample {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 is running");
try {
Thread.sleep(2000); // 摹拟线程1的履行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 is finished");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 is running");
try {
Thread.sleep(3000); // 摹拟线程2的履行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 is finished");
});
thread1.start();
thread2.start();
thread1.join(); // 等待线程1履行完成
thread2.join(); // 等待线程2履行完成
System.out.println("All threads are finished");
}
}
```
在上述示例中,我们创建了两个线程(thread1和thread2),它们分别打印一些信息并休眠一段时间。在主线程中,我们顺次调用thread1.join()和thread2.join()方法,从而等待这两个线程履行完成。最后打印"All threads are finished"表示所有线程履行完成。
注意:join()方法会抛出InterruptedException异常,因此需要进行异常处理。