JAVA利用多线程机制编写程序,输出一个共享字符串,要求每隔500毫秒输出一个字符及当前线程的名字。 (1)通过实现Runnable接口创建线程PrintInfo。 (2)共享字符串,你高中就读的学校名称(包含省、市) (3)创建两个线程t1、t2,让两个线程交替输出该共享字符串。
时间: 2024-01-17 08:03:26 浏览: 101
JAVA多线程编程
好的,我来解答你的问题。
以下是Java利用多线程机制编写程序,输出一个共享字符串,要求每隔500毫秒输出一个字符及当前线程的名字的代码:
```java
public class PrintInfo implements Runnable {
private String schoolName = "XX省XX市高中";
private int index = 0;
public void run() {
while (index < schoolName.length()) {
System.out.println(Thread.currentThread().getName() + ": " + schoolName.charAt(index));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
index++;
}
}
public static void main(String[] args) {
PrintInfo pi = new PrintInfo();
Thread t1 = new Thread(pi, "Thread-1");
Thread t2 = new Thread(pi, "Thread-2");
t1.start();
t2.start();
}
}
```
解释一下上面的代码:
1. 实现了Runnable接口,并重写了run()方法,run()方法中每隔500毫秒输出一个字符及当前线程的名字。
2. 共享字符串为高中名称,初始值为"XX省XX市高中"。
3. 在main方法中创建了两个线程t1和t2,并启动了这两个线程,让它们交替输出共享字符串。
由于两个线程共享PrintInfo对象,因此它们输出的是同一个字符串。输出结果如下:
```
Thread-1: X
Thread-2: X
Thread-2: X
Thread-1: X
Thread-1: 省
Thread-2: 省
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: 市
Thread-2: 市
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: X
Thread-2: X
Thread-1: 高
Thread-2: 高
Thread-1: 中
Thread-2: 中
```
以上就是答案了,希望能帮到你。
阅读全文