码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步引发的问题

时间:2015-09-13 15:51:02      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!