java线程同步方法论

2021-12-23  本文已影响0人  千千雪人

线程同步

  • 当有多个方法都加了synchronized锁的时候,多个线程在同一时间内只能有一个synchronized方法被一个线程执行

实验代码

package com.kakarote.crm.common;

import lombok.SneakyThrows;
import org.apache.commons.collections4.list.TreeList;

import java.util.*;

public class Test {
    public static void main (String[] args) throws InterruptedException {
        Thrett t = new Thrett();
        Thread th = new Thread(t);
        th.start();

        t.m2();
        System.out.println(t.b);
    }
}

class Thrett implements Runnable{
    public int b = 1000;

    public  synchronized void m1() throws InterruptedException {
//        b=5000;
        System.out.println("m1-来了");
        Thread.sleep(5000);
        System.out.println("m1----"+b);
    }
    public synchronized void m2() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("m2-来了");
        b=2000;
        System.out.println("m2----"+b);
    }
    @SneakyThrows
    @Override
    public void run() {
        m1();

    }
}

java wait与sleep的区别

上一篇下一篇

猜你喜欢

热点阅读