为了避免在同一时刻对同一个资源有多个线程访问造成的不可预知问题, 所以采用线程的同步机制
–代码中的同步机制
- –synchronized(同步锁)关键字的作用就是利用一个特定的对象设置一个锁lock, 在多线程并发访问的时候, 同事只允许一个线程, 可以获得这个锁, 执行特定的代码, 执行之后释放锁, 继续有其他线程争抢
–Synchronize的使用场景
- –synchronized代码块 - 任意对象即可
- –synchronized方法 - this当前对象
- –synchronized静态方法 - 该类的字节码对象
–示例代码
package com.ygq.thread;
import java.util.Random;
/**
* @author :GQ.Yin
* @date :Created in 2019/7/19 17:39
* @description:多线程的同步机制
* @version: $version$
*/
public class SyncSample {
public static void main(String[] args) {
final Couplet c = new Couplet();
for (int i = 0; i < 10000; i++) {
new Thread(){
@Override
public void run() {
int r = new Random().nextInt(2);
if (r%2 == 0){
c.first();
}else{
c.second();
}
}
}.start();
}
}
}
class Couplet {
/**synchronized同步代码块示例*/
Object lock = new Object(); //锁对象
public void first() {
synchronized (lock){ //同步代码块, 在同一时刻, 只允许有一个线程执行这个方法
System.out.printf("琴");
System.out.printf("瑟");
System.out.printf("琵");
System.out.printf("琶");
System.out.println();
}
}
public void second() {
synchronized (lock){ //同步代码块, 在同一时刻, 只允许有一个线程执行这个方法
//因为两个同步代码块, 指向了同一把锁,所以在同一个时间内只允许执行一个代码块
System.out.printf("魑");
System.out.printf("魅");
System.out.printf("魍");
System.out.printf("魉");
System.out.println();
}
}
/**synchronized方法示例*/
public synchronized void first(){ //synchronized方法, 直接在方法上加synchronized修饰即可
//当两个方法想要互斥的时候, 需要获取同一把锁,
//synchronized方法的时候, 默认指向this对象
System.out.printf("魑");
System.out.printf("魅");
System.out.printf("魍");
System.out.printf("魉");
System.out.println();
}
public void second() {
synchronized (this){
System.out.printf("魑");
System.out.printf("魅");
System.out.printf("魍");
System.out.printf("魉");
System.out.println();
}
}
/**synchronized静态方法*/
// public synchronized static void first(){ //synchronized静态方法, 直接在方法上加synchronized修饰即可
// //当两个方法想要互斥的时候, 需要获取同一把锁,
// //synchronized方法的时候, 指向该类的字节码对象
// System.out.printf("魑");
// System.out.printf("魅");
// System.out.printf("魍");
// System.out.printf("魉");
// System.out.println();
// }
//
// public void second() {
// synchronized (Couplet.class){ //锁定类对象
// System.out.printf("魑");
// System.out.printf("魅");
// System.out.printf("魍");
// System.out.printf("魉");
// System.out.println();
// }
// }
}