多线程写两个死循环
时间: 2023-07-01 14:18:29 浏览: 61
好的,以下是一个使用 Python 多线程模块编写的例子:
```python
import threading
def loop1():
while True:
print("Loop 1")
def loop2():
while True:
print("Loop 2")
t1 = threading.Thread(target=loop1)
t2 = threading.Thread(target=loop2)
t1.start()
t2.start()
```
这个例子中,我们定义了两个死循环函数 `loop1` 和 `loop2`,然后创建了两个线程 `t1` 和 `t2` 来同时运行这两个函数。通过 `start` 方法启动线程后,两个死循环会同时运行,并且不会相互影响。
相关问题
使用java 多线程写两个死循环
好的,以下是一个使用 Java 多线程编写的例子:
```java
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("Loop 1");
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("Loop 2");
}
}
});
t1.start();
t2.start();
}
}
```
这个例子中,我们创建了两个实现了 `Runnable` 接口的类 `Loop1` 和 `Loop2`,并且在 `run` 方法中定义了两个死循环。然后,我们创建了两个线程 `t1` 和 `t2` 来分别运行这两个类,并通过 `start` 方法启动线程。这样,两个死循环就会同时运行,并且不会相互影响。
python多线程死循环
以下是一个使用Python多线程实现死循环的例子:
```python
import threading
def loop():
while True:
pass
# 创建两个线程并启动
thread1 = threading.Thread(target=loop)
thread2 = threading.Thread(target=loop)
thread1.start()
thread2.start()
```
上述代码中,我们定义了一个名为`loop`的函数,该函数包含一个无限循环`while True`。然后,我们使用`threading.Thread`类创建了两个线程,并将`loop`函数作为目标函数传递给线程对象。最后,我们分别启动了这两个线程。
这样,两个线程将同时执行`loop`函数中的死循环,实现了Python多线程的死循环操作。