定义方法,接收字符串,利用for循环 遍历字符串 charAt打印,两个线程,一个线程打印出8个A,一个线程打印出8个B,调用同一个方法
时间: 2024-04-07 19:33:56 浏览: 14
以下是定义一个方法,接收字符串并利用循环遍历字符串的每个字符,并且使用两个线程,一个线程打印出8个A,另一个线程打印出8个B:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
Thread t1 = new Thread(() -> {
printChars(str, 'A', 8);
});
Thread t2 = new Thread(() -> {
printChars(str, 'B', 8);
});
t1.start();
t2.start();
}
public static void printChars(String str, char ch, int count) {
for (int i = 0; i < count; i++) {
System.out.print(ch);
try {
Thread.sleep(100); // 睡眠100毫秒,以便观察输出顺序
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,我们定义了一个`printChars`方法,它接收一个字符串(str)、一个字符(ch)和一个打印次数(count)作为参数。
在方法内部,我们使用`for`循环来遍历字符串,并使用`System.out.print(ch)`打印字符。为了模拟多线程的并发执行,我们在每次打印之后使用`Thread.sleep(100)`让线程睡眠100毫秒。
在`main`方法中,我们创建了两个线程(t1和t2),分别调用`printChars`方法打印出8个A和8个B。
请注意,由于线程的执行顺序是不确定的,输出的顺序可能会有所不同。但是,最终的结果应该是每个线程按照指定次数打印出相应的字符。