多线程中synchronized简单使用

作用是给某个对象加上锁,加锁的场景如图所示

 

 

其中

 

 和

 

 是等价的

 synchronized使用前

 

  synchronized使用后

 

 代码如下

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.java.test.synchronize;
 
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
 
/**
 * @author yourheart
 * @Description
 * @create 2022-10-20 8:09
 */
@Data
@NoArgsConstructor
@Slf4j
public class Account {
 
    /**
     * 账户编号
     */
    private String accountNo;
 
    /**
     * 余额
     */
    private double balance;
 
    public Account(String accountNo, double balance) {
        log.info("accountNo:{},balance:{}",accountNo,balance);
        this.accountNo = accountNo;
        this.balance = balance;
    }
 
    /**
     * 提供一个raw方法来完成取钱操作
     *
     * @param drawAccount
     */
    public synchronized void draw(double drawAccount) {
        //  账户余额大于所取的钱数
        if (balance >= drawAccount) {
            // 吐出钞票
            log.info("线程名称:{},取钱成功!吐出钞票:{}", Thread.currentThread().getName(), drawAccount);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 修改余额
            balance -= drawAccount;
            log.info("余额为:{}", balance);
        } else {
            log.info("线程名称:{} 取钱失败!余额不足!", Thread.currentThread().getName());
        }
    }
 
    @Override
    public String toString() {
        return "Account{" +
                "accountNo='" + accountNo + '\'' +
                ", balance=" + balance +
                '}';
    }
}

  

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
package com.java.test.synchronize;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2022/10/20 14:48
 */
@RestController
@Slf4j
public class DrawController {
 
    @RequestMapping("/threadTest")
    public String threadTest(){
        Account account = new Account("1234567", 1000);
        log.info("开始启动线程......");
        new DrawThread("甲", account, 300).start();
        new DrawThread("乙", account, 500).start();
        new DrawThread("丙", account, 400).start();
        log.info("线程调用结束....");
        return "线程调用结束....";
    }
}

  

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
package com.java.test.synchronize;
 
import lombok.extern.slf4j.Slf4j;
 
/**
 * @author yourheart
 * @Description
 * @create 2022-10-20 8:10
 */
@Slf4j
public class DrawThread extends Thread {
 
 
    private Account account;
    /*
     *当前线程所希望取到的钱数
     */
    private double drawAccount;
 
    public DrawThread(String name, Account account, double drawAccount) {
        super(name);
        this.account = account;
        this.drawAccount = drawAccount;
    }
 
    @Override
    public void run() {
        account.draw(drawAccount);
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.java.test;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2022/10/20 15:32
 */
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class,args);
    }
}

  

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.java</groupId>
    <artifactId>test-study</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>
 
    <dependencies>
        <!--tomcat容器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
        <!--引入junit单元测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
 
    </dependencies>
 
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>study</finalName>
    </build>
 
 
</project>

  Synchronized保证了同一时间只有一个线程在共享数据,其他的线程必须等待该线程处理结束,同时产生了互斥锁

 

posted @   不忘初心2021  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示