美文网首页
Synchronize线程同步机制

Synchronize线程同步机制

作者: c_gentle | 来源:发表于2021-04-21 08:34 被阅读0次

代码中的同步机制
synchronized(同步锁)关键字的作用就是利用一个特定的对象设置一个锁lock(绣球),在多线程(游客)并发访问的时候,同时只允许一个线程(游客)可以获得这个锁,执行特定的代码(迎娶新娘)。执行后释放锁,继续由其他线程争抢。
Synchronize的使用场景
Synchronize可以使用在以下三种场景,对应不同锁对象:
– synchronized代码块 - 任意对象即可
– synchronized方法 - this当前对象
– synchronized静态方法 - 该类的字节码对象

package com.caiweiwei.thread;
import java.util.Random;
public class SyncSample {
    public static void main(String[] args) {
        Couplet c = new Couplet();
        for(int i = 0 ; i < 10000 ; i++){
            new Thread(){
                public void run(){
                    int r = new Random().nextInt(2);
                    if(r % 2 == 0){
                        Couplet.first();
                    }else{
                        Couplet.second();
                    }
                }
            }.start();
        }
    }
}
class Couplet{
    Object lock = new Object(); //锁对象
    public synchronized static void first(){
//        synchronized (lock) { //同步代码块,在同一时间只允许有一个线程执行访问这个方法
            System.out.printf("琴");
            System.out.printf("瑟");
            System.out.printf("琵");
            System.out.printf("琶");
            System.out.println();
//        }
    }
    public static void second(){
        synchronized (Couplet.class) { //因为两个同步代码指向了同一把锁lock,所以在同一个时间内只允许有一个代码块执行,其他等待
            System.out.printf("魑");
            System.out.printf("魅");
            System.out.printf("魍");
            System.out.printf("魉");
            System.out.println();
        }

    }
}

相关文章

网友评论

      本文标题:Synchronize线程同步机制

      本文链接:https://www.haomeiwen.com/subject/eainlltx.html