为什么80%的码农都做不了架构师?>>>
1.不加锁的情况
package test.thread;
import java.util.concurrent.locks.ReentrantLock;
public class TestSyncCurrent {
public static void main(String[] args) {
Shop shop = new Shop();
Runnable r1 = new Client(shop, 500);
Runnable r2 = new Client(shop, 1000);
Runnable r3 = new Client(shop, 1500);
Runnable r4 = new Client(shop, 500);
Runnable r5 = new Client(shop, 1000);
Runnable r6 = new Client(shop, 1500);
new Thread(r1).start();
new Thread(r2).start();
new Thread(r3).start();
new Thread(r4).start();
new Thread(r5).start();
new Thread(r6).start();
new Thread(r1).start();
new Thread(r2).start();
new Thread(r3).start();
System.out.println("main:" + Thread.currentThread().getName());
}
public static class Shop{
ReentrantLock lock = new ReentrantLock();
private int count = 0;
//volatile int count = 0;
public int add(long delay){
try {
System.out.println(Thread.currentThread().getName() + ":add:start:");
//lock.lock();
Thread.sleep(delay);
count ++;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally{
//lock.unlock();
System.out.println(Thread.currentThread().getName() + ":add:end:");
}
return count;
}
}
public static class Client implements Runnable {
private Shop shop;
private long delay;
public Client(Shop shop, long delay) {
this.shop = shop;
this.delay = delay;
}
@Override
public void run() {
for(int i=0; i<10; i++) {
try {
//Thread.sleep(500);
int ret = shop.add(delay);
System.out.println("result:" + ret);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
9 个线程,每个线程运行10次,count结果应该是 90,实验大致结果: 60 < count < 88 浮动, 运行时间约为: 15秒
2. count 使用 volatile 修饰 结果 与 1 大致相同,求解释哪里出问题了。
3. ReentrantLock 加锁后,结果正确,运行时间: 90秒
具体结果正在分析中。