用Java定义方法,接收字符串,for循环 charAt打印,两个线程,调用同一个方法
时间: 2024-04-07 17:33:12 浏览: 14
好的,下面是用Java定义的方法,可以接收一个字符串,并使用两个线程同时调用该方法进行打印:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
PrintThread thread1 = new PrintThread(str);
PrintThread thread2 = new PrintThread(str);
thread1.start();
thread2.start();
}
static class PrintThread extends Thread {
private final String str;
public PrintThread(String str) {
this.str = str;
}
@Override
public void run() {
printString(str);
}
private synchronized void printString(String str) {
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
```
以上代码定义了一个 `PrintThread` 类,该类继承自 `Thread` 类,并且在 `run` 方法中调用了 `printString` 方法。`printString` 方法使用 synchronized 修饰符来保证线程安全,以确保两个线程不会同时访问该方法。在 `printString` 方法内部,使用 for 循环和 `charAt` 方法来逐个打印字符串中的字符。
通过创建两个 `PrintThread` 对象,并调用其 `start` 方法,可以启动两个线程同时调用 `printString` 方法打印相同的字符串。输出结果将是字符串中的字符按顺序打印出来。
希望对你有所帮助!如果还有其他问题,请继续提问。