实现效果

代码
使用到sleep的部分都是非必要的,只是sleep可以让结果不要一次性全部出来,比较好看
public class ThreadDemo extends Thread{
public static void main(String []args){
Numbers one = new Numbers();
Letters let = new Letters();
Thread two = new Thread(let);
one.start();
two.start();
}
}
class Numbers extends Thread {
@Override
public void run() {
synchronized (ThreadDemo.class) {
for(int i = 0; i < 5; i++){
for (int j = 1; j <=10; j++) {
System.out.print(j + " ");
}
System.out.println();
try {
Thread.sleep(1000);
ThreadDemo.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
ThreadDemo.class.notify();
}
}
}
}
class Letters implements Runnable {
@Override
public void run() {
synchronized (ThreadDemo.class) {
for(int i = 0; i < 5; i++){
for (int j = 0; j <= 25; j++) {
System.out.print((char) (65 + j) + " ");
}
System.out.println();
ThreadDemo.class.notify();
try {
Thread.sleep(1000);
ThreadDemo.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
本文档展示了如何使用Java的synchronized和wait/notify机制实现两个线程(Number和Letter)的并发执行,每个线程分别打印数字和字母序列,通过睡眠和同步控制输出节奏。
636

被折叠的 条评论
为什么被折叠?



