首页 > 编程语言 >浅谈Java实现线程同步&互斥

浅谈Java实现线程同步&互斥

时间:2022-10-22 20:00:46浏览次数:57  
标签:poolExecutor Java 浅谈 void private 互斥 static value new

先说简单的,Java实现线程互斥:

无线程互斥的情况

/**
 * @desc: 没有进行互斥的情况
 * @author: YanMingXin
 * @create: 2021/12/19-18:02
 **/
public class Method0 {

    private int value = 10;

    private void reduce() {
        try {
            while (value == 0) {
                System.out.println("stop...");
                return;
            }
            System.out.println(Thread.currentThread().getName() + ":" + value);
            value--;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        for (int i = 0; i < 20; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
    }

    public static void main(String[] args) {
        Method0 methodA = new Method0();
        methodA.make();
    }

}

方式一:互斥锁synchronized

/**
 * @desc: 互斥方式一
 * @author: YanMingXin
 * @create: 2021/12/19-17:48
 **/
public class MethodA {

    private int value = 10;

    private synchronized void reduce() {
        try {
            while (value == 0) {
                System.out.println("stop...");
                return;
            }
            System.out.println(Thread.currentThread().getName() + ":" + value);
            value--;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        for (int i = 0; i < 20; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
    }

    public static void main(String[] args) {
        MethodA methodA = new MethodA();
        methodA.make();
    }

}

方式二:可重入互斥锁ReentrantLock

/**
 * @desc: 互斥方式二
 * @author: YanMingXin
 * @create: 2021/12/19-17:50
 **/
public class MethodB {

    private int value = 10;

    private ReentrantLock lock=new ReentrantLock();


    private void reduce(){
        lock.lock();
        try {
            while (value == 0) {
                System.out.println("stop...");
                return;
            }
            System.out.println(Thread.currentThread().getName() + ":" + value);
            value--;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        for (int i = 0; i < 20; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
    }

    public static void main(String[] args) {
        MethodB methodA = new MethodB();
        methodA.make();
    }

}

然后,Java实现线程同步:

无线程同步的情况

/**
 * @desc: 无线程同步状态
 * @author: YanMingXin
 * @create: 2021/12/19-17:47
 **/
public class Method0 {

    private int value = 0;

    private static List list = new ArrayList<String>();

    static {
        list = Arrays.asList("1-Insert", "2-Delete", "3-Update", "4-Select");
    }

    private void reduce() {
        try {
            System.out.println(list.get(value));
            value++;
            while (value > 3) {
                System.out.println("stop...");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,
                4,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        for (int i = 0; i < 4; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
        poolExecutor.shutdown();
    }

    public static void main(String[] args) {
        Method0 methodA = new Method0();
        methodA.make();
    }

}

方式一:synchronized进行线程同步

/**
 * @desc: 线程同步方式一
 * @author: YanMingXin
 * @create: 2021/12/19-17:47
 **/
public class MethodA {

    private int value = 0;

    private static List list = new ArrayList<String>();

    static {
        list = Arrays.asList("1-Insert", "2-Delete", "3-Update", "4-Select");
    }

    private synchronized void reduce() {
        try {
            System.out.println(list.get(value));
            value++;
            while (value > 3) {
                System.out.println("stop...");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,
                4,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        for (int i = 0; i < 4; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
        poolExecutor.shutdown();
    }

    public static void main(String[] args) {
        MethodA methodA = new MethodA();
        methodA.make();
    }

}

方式二:ReentrantLock进行线程同步

/**
 * @desc: 线程同步方式二
 * @author: YanMingXin
 * @create: 2021/12/19-17:47
 **/
public class MethodA {

    private int value = 0;

    private ReentrantLock lock = new ReentrantLock();

    private static List list = new ArrayList<String>();

    static {
        list = Arrays.asList("1-Insert", "2-Delete", "3-Update", "4-Select");
    }

    private void reduce() {
        lock.lock();
        try {
            System.out.println(list.get(value));
            value++;
            while (value > 3) {
                System.out.println("stop...");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,
                4,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        for (int i = 0; i < 4; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
        poolExecutor.shutdown();
    }

    public static void main(String[] args) {
        MethodA methodA = new MethodA();
        methodA.make();
    }

}

方式三:synchronized代码块

/**
 * @desc: 线程同步方式三
 * @author: YanMingXin
 * @create: 2021/12/19-17:47
 **/
public class MethodA {

    private int value = 0;

    private static List list = new ArrayList<String>();

    static {
        list = Arrays.asList("1-Insert", "2-Delete", "3-Update", "4-Select");
    }

    private void reduce() {
        synchronized (this) {
            try {
                System.out.println(list.get(value));
                value++;
                while (value > 3) {
                    System.out.println("stop...");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void make() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,
                4,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        for (int i = 0; i < 4; i++) {
            poolExecutor.execute(() -> {
                reduce();
            });
        }
        poolExecutor.shutdown();
    }

    public static void main(String[] args) {
        MethodA methodA = new MethodA();
        methodA.make();
    }

}

标签:poolExecutor,Java,浅谈,void,private,互斥,static,value,new
From: https://blog.51cto.com/u_15654567/5786101

相关文章

  • java基础---报错为找不到或无法加载主类 HelloWorld1
    错误:找不到或无法加载主类HelloWorld1一、报错描述错误描述:在idea软件中编写HelloWorld1.java文件并运行成功。 packagecom.dysunlin.chapter01;/***@author......
  • JAVA---ArrayList的add底层源码分析
    1.ArrayList   无参构造器使用ArrayList源码1.首先创建了一个空的elementData数组2.add()方法添加第一个元素,如果是值类型来说,往ArrayList里面添加和修改元素,都......
  • java基础HashSet 集合TreeSet集合
           ......
  • Java中的JDK和JRE
    三个概念:JDK:javadevelopmentkit(java开发工具)JRE:javaruntimeenvironment(java运行时环境)JVM:javaVirtualMachine(java虚拟机)1.JDK:JDK就是我们开发人员使用的开发工具,......
  • java基础-->变量
    字面量计算机是用来处理数据的,字面量就是告诉程序员:数据在程序中的书写格式。常用数据生活中的写法程序中的写法说明整数666,-88666,-88写法一致小数13.......
  • Java限流及常用解决方案
    前言随着微服务的流行,服务和服务之间的依赖越来越强,调用关系越来越复杂,服务和服务之间的稳定性越来越重要。在遇到突发的请求量激增,恶意的用户访问,亦或请求频率过高给下游......
  • 选择排序与冒泡排序(c语言+Java语言)
    选择排序O(n2)首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。重复第二步,直到所有元素......
  • java 复杂对象数组练习 添加和遍历
       Javabeanpackagetest_4;publicclassStudent{privateintid;privateStringname;privateintage;publicStudent(){}publicStu......
  • java第四讲-继承与多态-InheritsAndPolymorphismSourceCode
    1.继承条件下类的访问权限public:外界可自由访问;private:外界不可访问;protected:同一包中的子类都可以访问,另一包中的子类(派生于同一个父类)也可以访问;default:如果......
  • java---泛型(Generics)
    泛型是JDK1.5以后增加的,它可以帮助我们建立类型安全的集合。什么是泛型泛型的本质就是“数据类型的参数化”,处理的数据类型不是固定的,而是可以作为参数传入,可以把“泛......