专栏首页掌上编程高并发编程系列
原创

高并发编程系列

高并发编程系列(一)

High concurrency programming series

对某个对象加锁

public class Ta {

    /**
     * synchronized keyword 
     * Locks an object
     */

    private int count = 10;

    private Object o = new Object();

    public void m(){
        synchronized(o){
            count--;
            System.out.println(Thread.currentThread().getName() + "count:" + count);
        }
    }

}

等同于在方法的代码执行时要synchronized

public class Tb {

    /**
     * Is equivalent to synchronized when the method's code executes.
     */

    private int count = 10;

    private Object o = new Object();

    public synchronized void m() {
            count--;
            System.out.println(Thread.currentThread().getName() + "count:" + count);
    }

}

**任何线程执行下面代码,必须要拿到this 的锁,

记住锁定的时对象 不是代码块 表面看着是代码块**

public class Tc {

    /**
     * Any thread that executes the following code must get the lock for this,
     * Remember that the object that is locked is not a block of code and it looks like a block of code
     */

    private int count = 10;

    public void m() {
        synchronized(this) {
            count--;
            System.out.println(Thread.currentThread().getName() + "count:" + count);
        }
    }

}

放在静态方法上面,由于静态没有this可以锁定,不需要new 出对象,运用了反射.

public class Td {

    /**
     * On the static method, because static no this can be locked, do not need to new out of the object, the use of reflection.
     */

    private static int count = 10;

    private Object o = new Object();

    public synchronized static void m() {
            count--;
            System.out.println(Thread.currentThread().getName() + "count:" + count);
    }

    public void mm() {
        synchronized(Td.class) {  //考虑一下这里写 synchronized (this)  是否可以  不可以
            count--;
            System.out.println(Thread.currentThread().getName() + "count:" + count);
        }
    }

}
public class Te implements Runnable {

    private int count = 10;

    @Override
    public synchronized void run() {
        count --;
        System.out.println(Thread.currentThread().getName() + "count:" + count);
    }

    public static void main(String[] args) {

        Te t = new Te();
        for (int i = 0; i<5;i++){
            new Thread(t,"THREAD" + i).start();
        }

    }
    
}

m1不影响m2,同步方法不影响其他方法,m2 不需要锁.

public class Tf {

    /**
     *
     * M1 does not affect m2, synchronous methods do not affect other methods, and m2 does not need a lock.
     */

    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "m1.start....");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "m1.end");
    }

    public void m2() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "m2");
    }

    public static void main(String[] args) {
        Tf t = new Tf();

        new Thread(()->t.m1()).start();
        new Thread(()->t.m2()).start();

        /*new Thread(t::m1,"t1").start();
        new Thread(t::m2,"t2").start();*/

       /* new Thread(new Runnable() {
            @Override
            public void run() {
                t.m1();
            }
        });*/

    }

}

**对业务写方法加锁.

对业务读方法不加锁.

容易产生脏读问题(dirtyRead).**

public class Tg {

    /**
     *
     * Locks the business write method.
     * Business read methods are not locked.
     * DirtyRead is easy to produce.
     * No two seconds sleep, no problem, plus there's a dirty read on the read,
     * there's a block of code between two seconds that might be executed by some other program that's not locked.
     * Lock or no lock depends on the business.
     * Tg For the account class  It has a name and a balance
     *
     */

    String name;
    double balance;

    public synchronized void set(String name, double balance) {
        this.name = name;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        this.balance = balance;
    }

    public /*synchronized*/ double getBalance(String name) {
        return this.balance;
    }

    public static void main(String[] args) {
        Tg t = new Tg();
        new Thread(()->t.set("掌上编程",100.0)).start();

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

        System.out.println(t.getBalance("掌上编程"));

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(t.getBalance("掌上编程"));

    }

}
运行结果

**一个同步方法可以调用另外一个同步方法,一个线程已经拥有某个对象,再次申请的时候仍然会得到该对象的锁,

也就是说synchronized 获得锁是可重入的。**

public class Th {

    /**
     *
     * One synchronized method can call another, and a thread that already owns an object will still get its lock when it requests it again.
     * That is, synchronized acquired locks are reentrant.
     */

    synchronized void m1() {
        System.out.println("m1.start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        m2();
    }

    synchronized void m2() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m2");
    }

}

一个同步的方法可以调用另外一个同步方法.一个线程已经拥有某个对象的锁,再次申请的时候仍然会得到该对象的锁.也就是说 synchronized获得的锁是可重入的.这里是继承中有可能发生的情形,子类调用父类的同步方法.

public class Ti {
    synchronized void m() {
    
        System.out.println("m.start");
        try{
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m.end");
    }

    public static void main(String[] args) {
        new TiTi().m();
    }

}

class TiTi extends Ti {

    @Override
    synchronized void m(){
        System.out.println("child m start");
        super.m();
        System.out.println("child m end");
    }

}
运行结果

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 高并发编程系列(一)

    放在静态方法上面,由于静态没有this可以锁定,不需要new 出对象,运用了反射.

    掌上编程
  • 记住:永远不要在 MySQL 中使用 UTF-8

    最近我遇到了一个bug,我试着通过Rails在以“utf8”编码的MariaDB中保存一个UTF-8字符串,然后出现了一个离奇的错误:

    掌上编程
  • 数据结构

    队列是数据结构中比较重要的一种类型,它支持 FIFO,尾部添加、头部删除(先进队列的元素先出队列),跟我们生活中的排队类似。

    掌上编程
  • 高并发编程系列(一)

    放在静态方法上面,由于静态没有this可以锁定,不需要new 出对象,运用了反射.

    掌上编程
  • Java并发-3.synchronized关键字

    Java中synchronized关键字作用是实现线程间的同步。它对同步的代码加锁,使得每次只能有一个线程进入同步快,以此保证线程间的安全性。 它的用法主要包...

    悠扬前奏
  • 二十五、Hystrix累计统计流、分发流、最大并发流、配置流、功能流(附代码示例)

    上篇文章 介绍了Hystrix的“主流”:在滑动窗口内统计流、健康流。既然Hystrix的指标数据收集是基于事件驱动,那么自然可以多一些监听流,那么本文将做个收...

    BAT的乌托邦
  • Java基础——Synchronized

    方法锁 synchronized修饰普通方法,不可以是静态方法,锁对象默认是this

    羊羽shine
  • 浅谈parallelStream 顶

    parallelStream是什么,它是一个集合的并发处理流.其作用是把一个集合中的数据分片,进行一个多线程的处理,增快运行速度.

    算法之名
  • Apache Hadoop入门

    介绍 本文要介绍的Apache Hadoop是一个使用简单高级编程模型实现的对大型数据集进行分布式存储和处理的软件框架。文章涵盖了Hadoop最重要的概念,对其...

    用户1263954
  • [WCF安全系列]绑定、安全模式与客户端凭证类型:NetNamedPipeBinding、NetTcpBinding与NetMsmqBinding

    在前面两篇(《绑定、安全模式与客户端凭证类型:BasicHttpBinding》和《绑定、安全模式与客户端凭证类型:WSHttpBinding与WSDualHt...

    蒋金楠

扫码关注云+社区

领取腾讯云代金券