两个线程交替打印100以内的数字
共享内存(不使用锁)
class test {
private static int count = 0;
public static void main(String[] args) {
Thread t1 = new MyThread(0);
Thread t2 = new MyThread(1);
t1.start();
t2.start();
}
private static class MyThread extends Thread {
private final int id;
private MyThread(int id) {
this.id = id;
}
@Override
public void run() {
while (count < 100) {
synchronized (this) {
if (count % 2 == id) {
System.out.println(Thread.currentThread().getName() + ":" + count);
count++;
}
}
}
}
}
}

浙公网安备 33010602011771号