java 多线程:Thread 并发线程: 方法同步synchronized关键字,与static的结合

1、方法内的变量是安全的

方法内定义的变量,每个变量对应单独的内存变量地址,多个线程之间相互不影响。多个线程之间的变量根本没有一毛钱关系

复制代码
public class ThreadFuncVarSafe {
    public static void main(String[] args) {
        Runnable r = () -> {
            String tmp ;
            String currentThreadName = Thread.currentThread().getName();
            if("A".equals(currentThreadName)){
                tmp = "I am A";
            }else {
                tmp = "I am B";
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread Name:" + currentThreadName + ",  func_var is:" + tmp);
        };
        Thread threadA = new Thread(r,"A");
        Thread threadB = new Thread(r,"B");
        threadA.start();
        threadB.start();
    }
}
复制代码

 

 2、实体变量线程不安全

复制代码
/**
 * @ClassName ThreadsClassVarNotSafe
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/22.
 */
public class ThreadsClassVarNotSafe {
    private static class MyRunnable implements Runnable{
        private String tmp;
        @Override
        public void run() {
            String currentThreadName = Thread.currentThread().getName();
            if("A".equals(currentThreadName)){
                tmp = "I am A";
            }else {
                tmp = "I am B";
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread Name:" + currentThreadName + ",  func_var is:" + tmp);
        }
    }

    public static void main(String[] args) {
        Runnable r = new MyRunnable();
        Thread threadA = new Thread(r,"A");     //同一个实体对象,最后输出被后执行的覆盖两个线程最后输出的结果一样都为A,或者都为B
        Thread threadB = new Thread(r,"B");     //同一个实体对象,最后输出被后执行的覆盖两个线程最后输出的结果一样都为A,或者都为B
//        Thread threadA = new Thread(new MyRunnable(),"A");//这种是不同的实体对象,相互无影响
//        Thread threadB = new Thread(new MyRunnable(),"B");//这种是不同的实体对象,相互无影响
        threadA.start();
        threadB.start();
    }
}
复制代码

 

...方法安全...

 3、方法用synchronized关键字修饰方法(方法安全),多线程遇到同一个对象的该方法变串行

同一个实体对象,对实体的方法加锁,多个线程调用同一个实体对象的 安全方法

复制代码
/**
 * @ClassName ThreadsClassVarNotSafe
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/22.
 */
public class ThreadsFuncSafe {
    private static class MyRunnable implements Runnable{
        private String tmp;

        @Override
        public synchronized void run() {
            String currentThreadName = Thread.currentThread().getName();
            if("A".equals(currentThreadName)){
                tmp = "I am A";
            }else {
                tmp = "I am B";
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread Name:" + currentThreadName + ",  func_var is:" + tmp);
        }
    }

    public static void main(String[] args) {
        Runnable r = new MyRunnable();
        Thread threadA = new Thread(r,"A");     //同一个实体对象,MyRunnable类run方法被synchronized修饰,只能一个线程持有run()方法执行权限,两个线程运行到run()变串行
        Thread threadB = new Thread(r,"B");     //同一个实体对象,MyRunnable类run方法被synchronized修饰,只能一个线程持有run()方法执行权限,两个线程运行到run()变串行
        threadA.start();
        threadB.start();
    }
}
复制代码

 

 4、多个实例多个锁,每个实例独立变量对象互不影响;实例外变量则有影响

示例:1、每个实例独立变量对象互不影响

复制代码
/**
 * @ClassName ThreadsClassVarNotSafe
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/22.
 */
public class ThreadsMultiObjectVarSafe {
    private static class MyRunnable implements Runnable{
        private String tmp;

        @Override
        public void run() {
            String currentThreadName = Thread.currentThread().getName();
            if("A".equals(currentThreadName)){
                tmp = "I am A";
            }else {
                tmp = "I am B";
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread Name:" + currentThreadName + ",  func_var is:" + tmp);
        }
    }

    public static void main(String[] args) {
        Thread threadA = new Thread(new MyRunnable(),"A");     //不同实体对象,方法无synchronized,变量独立互不影响
        Thread threadB = new Thread(new MyRunnable(),"B");     //不同实体对象,方法无synchronized,变量独立互不影响
        threadA.start();
        threadB.start();
    }
}
复制代码

 

 示例:2、多个线程实例修改实例外变量,不安全

复制代码
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName ThreadsMultiObjectOutofVarNotSafe
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/22.
 */
public class ThreadsMultiObjectOutofVarNotSafe {
    private static int num = 0;
    private static class MyThread extends Thread{
        @Override
        public synchronized void run() {
            for (int i=0; i<100000; i++){
                num ++;
            }
            System.out.println(getName() + "num:" + num);
        }
    }

    public static void main(String[] args) {
        Set<MyThread> threads = new HashSet<>();
        for (int i=0; i<5; i++){
            threads.add(new MyThread());
        }
        threads.forEach(thread ->thread.start());
        /**
         * 等待子线程结束再从main中获取num看值多少
         */
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main 线程中 sum最终为:" + num); //不足50万
    }
}
复制代码

运行结果,我们就算加上了synchronized关键字之后,结果依然可能会出现不正确,那是因为我们创建了5个实例,我们的synchronized会锁住当前的对象实例,而我们现在有5个实例,所以,我们多个线程的run方法不会被synchronized相互锁上,所以结果不正确。

5、同步synchronized静态static方法多实例之间安全

示例:多个线程对象调用同一个类实现的对象 的 synchronized修饰的静态static方法。被锁住的对象变为当前的类,而非对象,所以多个线程遇到此类方法顺序进行。

复制代码
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName ThreadsMultiObjectOutofVarNotSafe
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/22.
 */
public class ThreadsMultiObjectStaticFuncSyncSafe {
    private static int num = 0;
    private static class MyThread extends Thread{
        private static synchronized void safeRun(){
            for (int i=0; i<100000; i++){
                num ++;
            }
            System.out.println(Thread.currentThread().getName() + "   num:" + num);
        }
        @Override
        public void run() {
            safeRun();
        }
    }

    public static void main(String[] args) {
        Set<MyThread> threads = new HashSet<>();
        for (int i=0; i<5; i++){
            threads.add(new MyThread());
        }
        threads.forEach(thread ->thread.start());
        /**
         * 等待子线程结束再从main中获取num看值多少
         */
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main 线程中 sum最终为:" + num); //不足50万
    }
}
复制代码

每次的结果都是正确的,是500000,这个是为什么?

因为,我们在static的方法上面加上synchronized之后,锁的钥匙就变成了当前对象的Class属性(MimlThread.class)。class属性在java里面是一个元数据,元数据在JVM中只保存了一份,所以我们对这个class上锁之后,不同的线程调用,会被相互排斥。

6,异常发生的时候,锁会自动释放

如上代码safeRun()方法中num++上抛出异常,不影响其他线程运行。

                if(i >9){throw new RuntimeException();} //测试抛出异常后,是否影响其他线程,结果为 main 线程中 sum最终为:50
                num ++;

 

 

posted on   zhangmingda  阅读(396)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-04-22 深入理解css中position属性及z-index属性 https://www.cnblogs.com/zhuzhenwei918/p/6112034.html
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示