1. System.out.println方法是线程安全的
之前一直疑惑为啥下面案例中的主线程中num = 1会对线程A可见,注意没有加volatile修饰
class Test1{
//public volatile static int num =0;
public static int num =0;
public static void main(String[] args) {
new Thread(()->{
while (num==0){
System.out.println(Thread.currentThread().getName());
}
},"线程A").start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num = 1;
System.out.println(num);
}
}
后来百度一下知道原来println()方法是线程安全的
//println方法的实现
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
JMM关于Synchronized的两条规定:
线程加锁时,讲清空工作内存中共享变量的值,从而使用共享变量是需要从主内存中重新读取最新的值(加锁与解锁需要统一把锁)
线程解锁前,必须把共享变量的最新值刷新到主内存中;
2. 虚假唤醒
public class PcModel {
public static void main(String[] args){
SynResource synResource = new SynResource();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
synResource.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"生产者").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
synResource.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"生产者副本").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
synResource.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"消费者").start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
synResource.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"消费者副本").start();
}
}
class SynResource{
volatile private int count =0;
synchronized void increment() throws InterruptedException {
if (count == 1){
this.wait();
}
System.out.println(Thread.currentThread().getName() + "+ 1");
count++;
this.notifyAll();
}
synchronized void decrement() throws InterruptedException {
if (count == 0){
this.wait();
}
System.out.println(Thread.currentThread().getName() + "- 1");
count--;
this.notifyAll();
}
}
上面是一个经典的生产者-消费者模型。当只有一个生产者和一个消费者时程序能正常运行,但如果按照上面的例子来运行。可以发现运行结果并不是我们所想要的结果。这是因为if语句执行完后会接着向下执行,即当线程被唤醒重新获得锁后会接着向下运行,这时就会产生虚假唤醒的问题了(生产者和生产者副本都运行至this.wait()),如果把if语句改成while就能避免此中现象产生。
3. ReadWriteLock
- 如果当前是写锁被占有了,只有当写锁的数据降为0时才认为释放成功;否则失败。因为只要有写锁,那么除了占有写锁的那个线程,其他线程即不可以获得读锁,也不能获得写锁
- 如果当前是读锁被占有了,那么只有在写锁的个数为0时才认为释放成功。因为一旦有写锁,别的任何线程都不应该再获得读锁了,除了获得写锁的那个线程。
4. static synchronized 修饰的方法中
当前锁对象是 类.calss对象 注意与非静态方法的区别