Java 多线程同步常用的三种方法

一 、为什么要线程同步


因为当我们有多个线程要同时访问一个变量或对象时,如果这些线程中既有读又有写操作时,就会导致变量值或对象的状态出现混乱,从而导致程序异常。举个例子,如果一个银行账户同时被两个线程操作,一个取100块,一个存钱100块。假设账户原本有0块,如果取钱线程和存钱线程同时发生,会出现什么结果呢?取钱不成功,账户余额是100.取钱成功了,账户余额是0.那到底是哪个呢?很难说清楚。因此多线程同步就是要解决这个问题。

二、同步时的代码

1、synchronized锁住方法 同步方法

即有synchronized关键字修饰的方法。 由于java的每个对象都有一个内置锁,当用此关键字修饰方法时,内置锁会保护整个方法。在调用该方法前,需要获得内置锁,否则就处于阻塞状态。

<pre class="prettyprint hljs gradle" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">package com.company.model;

public class Bank {
private int count =0;//账户余额

//存钱 public synchronized void addMoney(int money){

    count +=money;
    System.out.println(System.currentTimeMillis()+"存进:"+money);
} //取钱 public synchronized void subMoney(int money){ if(count-money < 0){
        System.out.println("余额不足"); return;
    }
    count -=money;
    System.out.println(+System.currentTimeMillis()+"取出:"+money);
} //查询 public void lookMoney(){
    System.out.println("账户余额:"+count);
}

}</pre>

<pre class="hljs" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">测试方法:</pre>

<pre class="prettyprint hljs java" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">package com.company;

import com.company.model.Bank;

public class Main {

public static void main(String[] args) { // write your code here final Bank bank=new Bank();

    Thread tadd=new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(true){ try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
                }
                bank.addMoney(100);
                bank.lookMoney();
                System.out.println("\n");

            }
        }
    });

    Thread tsub = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(true){
                bank.subMoney(100);
                bank.lookMoney();
                System.out.println("\n"); try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
                }
            }
        }
    });
    tsub.start();

    tadd.start();
}

}</pre>

执行结果:

<pre class="prettyprint hljs" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">余额不足
账户余额:0

余额不足
账户余额:0

162****234927存进:100
账户余额:100

162****235935存进:100
账户余额:200

162****235935取出:100
账户余额:100

162****236944取出:100
账户余额:0</pre>

注: synchronized关键字也可以修饰静态方法,此时如果调用该静态方法,将会锁住整个类。

2、同步代码块

<pre class="prettyprint hljs gradle" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">package com.company.model;

public class Bank {
private int count =0;//账户余额

//存钱 public void addMoney(int money){ synchronized(this) {
        count += money;
    }
    System.out.println(System.currentTimeMillis()+"存进:"+money);
} //取钱 public void subMoney(int money){ if(count-money < 0){
        System.out.println("余额不足"); return;
    } synchronized(this) {
        count -= money;
    }
    System.out.println(+System.currentTimeMillis()+"取出:"+money);
} //查询 public void lookMoney(){
    System.out.println("账户余额:"+count);
}

}</pre>

效果和方法1差不多。

注:同步是一种高开销的操作,因此应该尽量减少同步的内容。通常没有必要同步整个方法,使用synchronized代码块同步关键代码即可。

3、使用重入锁实现线程同步

在JavaSE5.0中新增了一个java.util.concurrent包来支持同步。ReentrantLock类是可重入、互斥、实现了Lock接口的锁, 它与使用synchronized方法和块具有相同的基本行为和语义,并且扩展了其能力。ReenreantLock类的常用方法有:ReentrantLock() :创建一个ReentrantLock实例lock() :获得锁unlock() :释放锁注:ReentrantLock()还有一个可以创建公平锁的构造方法,但由于能大幅度降低程序运行效率,不推荐使用。

Bank.java代码修改如下:

<pre class="prettyprint hljs cs" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">package com.company.model;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Bank {
private int count = 0;//账户余额
//需要声明这个锁
private Lock lock = new ReentrantLock();

//存钱 public void addMoney(int money) {
    lock.lock(); //加锁 try {
        count += money;
        System.out.println(System.currentTimeMillis() + "存进:" + money);
    } catch (Exception e) {
        lock.unlock();//解锁 } finally {
        lock.unlock();//解锁 }
} //取钱 public void subMoney(int money) {
    lock.lock();//加锁 try { if (count - money < 0) {
            System.out.println("余额不足"); return;
        } synchronized (this) {
            count -= money;
        }
        System.out.println(+System.currentTimeMillis() + "取出:" + money);
    } catch (Exception e) {
        lock.unlock();//解锁 } finally {
        lock.unlock();//解锁 }
} //查询 public void lookMoney() {
    System.out.println("账户余额:" + count);
}

}</pre>

#java##程序员的日常#
全部评论
涨知识了,感谢分享
点赞 回复 分享
发布于 2022-07-15 13:10

相关推荐

12-08 16:04
门头沟学院 Java
本人本科末9,今年大三。大一大二一直玩,什么都没学到,在大学混日子混了两年,每天不是在打农就是在steam。大三开学时一个和自己玩的好的同学去实习了,才发现自己白白浪费了两年的时间,如果真不冲一下就真去京东,阿里,美团送外卖了今年9月份开始学Java,一开始一直跟着黑马视频看,后面发现看视频效率太低了,时间根本不够,就开始主要看文档和看书了。这几个月一直在学,真的尽力了,希望暑期前能找一份好点的实习。我简历上面的项目大多没有指标,但是实际上我是真没多少时间去做项目,我基本主要是动手只做了外卖和天机,黑马点评和12306我都是只是看了项目。主要是自己的时间真的不多,但是这样子自己的代码能力确实比较差。而且自己也没有做过实际的工程,我顶多用jmeter测试一下接口tps啥的,比如使用Redis管道提升了一点性能,减少Redis交互,这种值得写上去吗?需不需要具体到某些数字求求各位佬给一些建议,看看简历怎么优化?项目介绍是不是不够详细?没有具体到业务方面。项目会不会提到大致实现原理导致面试官一看简历就知道怎么实现就没有问的欲望?专业技能一些字段是不是要加粗,是不是写太啰嗦了?有没有必要压缩内容变成一页?两页的话是不是都要把两页填地满满的。
给秋招一个交代:一页简历最好,网上做的项目放面试官眼里都是玩具,简历上不需要强调有什么难点,记住就行防止真的问。然后背八股,多投多面试就行
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务