用Java编写两个线程一个线程输出a~z一个线程输出A~Z。要求输出格式如下:AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz
以下是Java代码实现:
public class PrintThread implements Runnable {
private char start;
private static Object lock = new Object();
public PrintThread(char start) {
this.start = start;
}
@Override
public void run() {
synchronized(lock) {
for (int i = 0; i < 26; i++) {
System.out.print((char)(start + i));
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new PrintThread('A'));
Thread thread2 = new Thread(new PrintThread('a'));
thread1.start();
thread2.start();
}
}
其中,PrintThread类实现了Runnable接口,实现了run方法。在run方法中,使用synchronized关键字实现了线程同步,并使用wait和notify方法实现了线程交替执行。在main方法中,创建了两个线程分别输出A~Z和a~z。运行程序,可以得到输出结果:
AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZ
原文地址: https://www.cveoy.top/t/topic/fI4c 著作权归作者所有。请勿转载和采集!