public class ThreadTest {
private volatile static int sum = 0;
static Object object = "";
static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
/* PipedReader out = new PipedReader();
PipedWriter in = new PipedWriter();
out.connect(in);
Thread thread = new Thread(new Print(in), "PrintThread");
thread.start();
int receive =0;*/
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(() -> {
// synchronized (object) {
lock.lock();
for (int j = 0; j < 10000; j++) {
sum++;
}
lock.unlock();
/*unlock() 尽量放在 finally{}里,因为如果上面逻辑有异常,不放finally,unlock不运行会一直锁住*/
// }
});
thread.start();
}
Thread.sleep(3000);
System.out.println(sum);
/*
* 打印结果47869 --> volatile 不保证原子性
* 1)synchronize : 线程较多时,线程阻塞会引起用内核态调用park方法,竞争比较激烈的场景会有性能问题
* 2)ReentrantLock
* 2)Atomic
*
* */
}
}
lock 相关
最新推荐文章于 2024-05-18 16:42:38 发布