关于线程锁作用对象的基础知识!

线程不同步,欲使用 synchronized 来同步锁,必须保证线程作用的是同一个对象!否则锁不起作用!

简单demo例子:

方式一:

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
32
33
34
35
36
37
38
39
40
package com.test;
 
public class Test10{
 
    //==单例对象!(对象不唯一,synchronized不起作用!)====================
    private Test10(){};//构造方法私有化
    private static Test10 t10;//对象私有化
    public static Test10 getOnly(){
        if(t10 == null){
            t10 = new Test10();
        }
        return t10;
    }
    //==多线程=======================
    public void init1(){
        new Thread(new Runnable() {
            public void run() {
                getOnly().con("生产");
            }
        }).start();
    }
    public void init2(){
        new Thread(new Runnable() {
            public void run() {
                getOnly().con("消费");
            }
        }).start();
    }
    //==线程间竞争的方法================
    public synchronized void con(String con){
        for(int i=0;i<1000;i++){
            System.out.println(con+i);
        }
    }
     
    public static void main(String[] args) {
        getOnly().init1();
        getOnly().init2();
    }
}

方式二:

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
32
33
34
35
36
37
38
39
package com.test;
 
public class Test11 {
     
    //==一个方法内多个线程=======================
    public void init1(){
         
        //只有一个对象!
        final Test11 t11 = new Test11();
         
        new Thread(new Runnable() {
            public void run() {
                t11.con("生产");
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                t11.con("消费");
            }
        }).start();
    }
     
    //==线程间竞争的方法================
    public synchronized void con(String con){
        for(int i=0;i<100;i++){
            System.out.println(con+i);
        }
    }
}
class Testxx{
     
    public static void main(String[] args) {
         
        final Test11 t11 = new Test11();
        t11.init1();
         
    }
     
}

  

posted @   雪化山河  阅读(429)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示