创建两个线程,分别循环10次,每一次循环会打印出当前线程名称与循环次数,之后休眠100毫秒。
时间: 2024-02-16 15:04:25 浏览: 50
好的,以下是创建两个线程并循环打印的Python代码:
```python
import threading
import time
def print_loop(thread_name):
for i in range(1, 11):
print(f"{thread_name} loop {i}")
time.sleep(0.1)
# 创建两个线程并启动
thread1 = threading.Thread(target=print_loop, args=("Thread 1",))
thread2 = threading.Thread(target=print_loop, args=("Thread 2",))
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
```
这段代码中,我们定义了一个`print_loop`函数,其中包含一个循环,每次循环打印当前线程名称以及循环次数,并休眠100毫秒。接着我们创建了两个线程,分别将`print_loop`函数作为线程的目标函数,并传入不同的线程名称作为参数。最后我们启动两个线程,并等待它们完成。
相关问题
Java语言创建两个线程,分别循环10次,每一次循环会打印出当前线程名称与循环次数,之后休眠100毫秒。
好的,以下是使用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`对象作为线程的目标对象,并传入不同的线程名称作为参数。最后我们启动两个线程,并等待它们完成。
1.创建两个线程,分别循环10次,每一次循环会打印出当前线程名称与循环次数,之后休眠100毫秒。 步骤如下: 1、创建线程类(通过实现Runnable接口) 2、重写run方法,在run方法中输出信息 3、休眠100毫秒 4、在主方法中开启两个线程
.next();
List<Student> studentListByName = manager.queryStudentByName(nameToQuery);
if (studentListByName.size() > 好的,以下是实现该功能的Java代码:
```java
public class MyThread implements Runnable {
private String threadName;
0) {
for (Student s : studentListByName) {
System.out.println(s);
}
} else {
System
public MyThread(String name) {
this.threadName = name;
}
public void run() {
for (int.out.println("找不到该姓名对应的学生信息!");
}
break;
case 6: // 根据 i = 1; i <= 10; i++) {
System.out.println(threadName + " " + i);
try {
关键字查询学生信息
System.out.println("请输入关键字:");
String keywordToQuery = scanner.next();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
List<Student> studentListByKeyword = manager.queryStudentByKeyword(keywordToQuery);
if (studentListByKeyword.size() > public static void main(String[] args) {
Thread t1 = new Thread(new MyThread("Thread 1"));
Thread t2 0) {
for (Student s : studentListByKeyword) {
System.out.println(s);
}
} else {
= new Thread(new MyThread("Thread 2"));
t1.start();
t2.start();
}
}
```
运行 System.out.println("找不到符合条件的学生信息!");
}
break;
case 0: // 退出程序
System.out.println("谢谢使用!");
System.exit(0);
default:
System.out.println("请输入正确以上代码,会创建两个线程,分别为“Thread 1”和“Thread 2”,每个线程循的操作编号!");
break;
}
}
}
}
```
这个程序可以通过控制台菜单来实环10次,每次循环会打印出当前线程名称和循环次数,之后休眠100毫秒现对学生信息的增、删、改、查等功能,并且使用文件读写操作来加载及保存记录信息。