同时启动2个线程,一个线程打印A,一个线程打印B,实现ABAB这样轮流打印,每个线程打印10次,如何实现?
时间: 2024-04-10 14:28:10 浏览: 25
您可以使用多线程的方式来实现ABAB轮流打印。下面是一个使用Python中的`threading`模块实现的示例代码:
```python
import threading
def print_a():
for _ in range(10):
print('A', end='')
def print_b():
for _ in range(10):
print('B', end='')
if __name__ == '__main__':
thread_a = threading.Thread(target=print_a)
thread_b = threading.Thread(target=print_b)
thread_a.start()
thread_b.start()
thread_a.join()
thread_b.join()
```
在上面的代码中,我们创建了两个线程`thread_a`和`thread_b`,分别用于打印字母A和B。每个线程循环打印10次,通过调用`start()`方法启动线程,然后调用`join()`方法等待线程执行完毕。
运行以上代码,您将会看到输出结果为`ABABABABABABABABABAB`,即实现了ABAB轮流打印的效果。
相关问题
同时启动2个线程,一个线程打印A,一个线程打印B,实现ABAB这样轮流打印,每个线程打印10次,用java如何实现?
在Java中,您可以使用多线程的方式来实现ABAB轮流打印。下面是一个使用Java的示例代码:
```java
class PrintThread implements Runnable {
private String message;
private int count;
public PrintThread(String message, int count) {
this.message = message;
this.count = count;
}
public void run() {
for (int i = 0; i < count; i++) {
System.out.print(message);
Thread.yield(); // 可选,用于让出CPU时间片
}
}
}
public class Main {
public static void main(String[] args) {
Thread threadA = new Thread(new PrintThread("A", 10));
Thread threadB = new Thread(new PrintThread("B", 10));
threadA.start();
threadB.start();
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们创建了一个`PrintThread`类实现`Runnable`接口,用于打印指定的消息。在`run()`方法中,使用一个循环打印指定次数的消息,并使用`Thread.yield()`方法(可选)让出CPU时间片。
在`Main`类中,我们创建了两个线程`threadA`和`threadB`,分别用于打印字母A和B。每个线程循环打印10次,通过调用`start()`方法启动线程,然后通过`join()`方法等待线程执行完毕。
运行以上代码,您将会看到输出结果为`ABABABABABABABABABAB`,即实现了ABAB轮流打印的效果。
找第一个只出现一次的字符
可以使用哈希表(字典)来实现。具体步骤如下:
1. 遍历字符串,使用哈希表记录每个字符出现的次数。
2. 再次遍历字符串,找到第一个出现次数为1的字符并返回。
以下是 Python 代码实现:
```python
def first_unique_char(s: str) -> str:
char_dict = {}
# 遍历字符串,记录每个字符出现的次数
for c in s:
char_dict[c] = char_dict.get(c, 0) + 1
# 再次遍历字符串,找到第一个出现次数为1的字符并返回
for c in s:
if char_dict[c] == 1:
return c
return ""
```
示例:
```python
s = "leetcode"
print(first_unique_char(s)) # 输出 l
s = "loveleetcode"
print(first_unique_char(s)) # 输出 v
s = "abab"
print(first_unique_char(s)) # 输出 ""
```