Java语言创建两个线程,分别循环10次,每一次循环会打印出当前线程名称与循环次数,之后休眠100毫秒。
时间: 2024-02-16 10:04:26 浏览: 52
好的,以下是使用Java语言创建两个线程并循环打印的代码:
```java
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new PrintLoop("Thread 1"));
Thread thread2 = new Thread(new PrintLoop("Thread 2"));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PrintLoop implements Runnable {
private String threadName;
public PrintLoop(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(threadName + " loop " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这段代码中,我们定义了一个`PrintLoop`类,实现了`Runnable`接口,其中包含一个循环,每次循环打印当前线程名称以及循环次数,并休眠100毫秒。接着我们创建了两个线程,分别将`PrintLoop`对象作为线程的目标对象,并传入不同的线程名称作为参数。最后我们启动两个线程,并等待它们完成。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)