认识线程之Synchronized(二)

本文主要探讨了Java中的Synchronized关键字,介绍了其在多线程环境中的作用,防止线程干扰和内存一致性错误。通过代码示例展示了synchronized如何工作,当多个线程运行时,未持有锁的线程将被阻塞,确保同一时刻只有一个线程执行同步代码块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

认识线程之Synchronized(二)

认识线程

  • 使用TimeUnit代替Thread.sleep()

synchronized

官方文档解释
Synchronized keyword enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object’s variables are done through synchronized methods.

代码

package com.jetty.test.thread;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Title:
 * Description:
 * Copyright: Copyright (c) 2019
 * Company: ChinaSteel
 * </p>
 *
 * @author: jetty
 * @create: 2019-09-24 15:57
 * @version:1.0
 */
public class Mutex {

    private final static Object MUTEX = new Object();

    public void accessResources(){

        synchronized (MUTEX){
            try {
                TimeUnit.SECONDS.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final Mutex mutex = new Mutex();
        for (int i = 0;i< 15;i++){
            new Thread(mutex::accessResources).start();
        }
    }

}

运行多个线程时,其他线程会被阻塞。
在这里插入图片描述
用jconsole查询
在这里插入图片描述
只会有一个线程进入sleeping状态,其他都进入blocked状态。
Synchronized同步的线程不可被中断
代码演示:

package com.jetty.test.thread;

import java.util.concurrent.TimeUnit;

/**
 1. <p>
 2. Title:
 3. Description:
 4. Copyright: Copyright (c) 2019
 5. Company: ChinaSteel
 6. </p>
 7.  * @author: jetty
 8. @create: 2019-09-25 14:08
 9. @version:1.0
 */
public class SynchronizedDefect {

    public synchronized void syncMethod(){
        try {

            TimeUnit.HOURS.sleep(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException{
        SynchronizedDefect defect = new SynchronizedDefect();
        Thread thread = new Thread(defect::syncMethod,"T1");
        thread.start();
        TimeUnit.MILLISECONDS.sleep(2);
        Thread thread2 = new Thread(defect::syncMethod,"T2");
        thread2.start();
        thread2.interrupt();
        System.out.println(thread2.isInterrupted());
        System.out.println(thread2.getState());
    }
}

console结果
true
BLOCKED

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值