多线程打印1~100:
public class MutillThread {
private static Lock lock = new ReentrantLock();
private static int state = 0;
private static int count = 1;
static class MyThread extends Thread {
int num;
public MyThread( int num) {
this.num = num;
}
@Override
public void run() {
while(count < 100) {
try{
lock.lock();
//这里要double check count <=100,不然最后一个线程已经通过了外层判断在这里等待会继续打印101
while(state % 4 == num && count <=100) {
System.out.println(Thread.currentThread().getName()+": "+count);
state++;
count++;
}
} finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
new MyThread( 0).start();
new MyThread( 1).start();
new MyThread(2).start();
new MyThread(3).start();
}
}
但是我没想明白count为什么不加voliatle也可以。
网友评论