package javatest.thread;
public class ThreadTest{
private static int state = 1;
private static int num1 = 1;
private static int num2 = 2;
public static void main(String[] args) {
final ThreadTest t = new ThreadTest();
new Thread(new Runnable() {
public void run() {
while (num1 < 100) {
synchronized(t) {
if (state != 1) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + num1);
num1 += 2;
state = 2;
t.notify();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (num2 < 100) {
synchronized(t) {
if (state != 2) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + num2);
num2 += 2;
state = 1;
t.notifyAll();
}
}
}
}).start();
}
}
java 线程交替打印1-100值
最新推荐文章于 2024-05-07 21:39:17 发布