问题描述
两个线程交替打印0到100:
偶数线程:0
基数线程:1
偶数线程:2
基数线程:3
偶数线程:4
基数线程:5
偶数线程:6
基数线程:7
......
......
简单实现
package test;
public class OdevityThread {
static class Soulution implements Runnable {
private static int value = 0;
@Override
public void run() {
while (value <= 100) {
synchronized (Soulution.class) {
System.out.println(Thread.currentThread().getName() + ":" + value++);
Soulution.class.notify();
try {
Soulution.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new Thread(new Soulution(), "偶数线程").start();
new Thread(new Soulution(), "奇数线程").start();
}
}