标签:
import java.util.concurrent.locks.ReentrantLock;
public class SerialNumberChecker implements Runnable {
private static volatile int serialNumber = 0;
static ReentrantLock lock = new ReentrantLock();
public static int nextSerialNumber() {
serialNumber = serialNumber + 1;
return serialNumber; // Not thread-safe
}
private int id = 0;
@Override
public void run() {
int temp = -1;
while (true) {
int serial = nextSerialNumber();
if (temp - serial > 0) {
System.out.println("id--" + id + " serial--" + serial + " temp--" + temp);
System.exit(0);
}
temp = serial;
}
}
public SerialNumberChecker(int id) {
this.id = id;
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 2; i++)
new Thread(new SerialNumberChecker(i)).start();
}
}
标签:
原文地址:http://www.cnblogs.com/shalf/p/4805007.html