java实现线程安全的三种方式

前言

一个程序在运行起来的时候会转换成进程,通常含有多个线程。通常情况下,一个进程中的比较耗时的操作(如长循环、文件上传下载、网络资源获取等),往往会采用多线程来解决。

比如现实生活中,银行取钱问题、火车票多个售票窗口的问题,通常会涉及到并发的问题,从而需要多线程的技术。

当进程中有多个并发线程进入一个重要数据的代码块时,在修改数据的过程中,很有可能引发线程安全问题,从而造成数据异常。例如,正常逻辑下,同一个编号的火车票只能售出一次,却由于线程安全问题而被多次售出,从而引起实际业务异常。

我们在不对多线程数据进行保护的情况下会引发的状况如下:

package com.example.springbooxianchengchi.xcc;

public class ThreadUnSecurity {

    static int tickets = 10;

    class SellTickets implements Runnable {

        @Override
        public void run() {
            // 未加同步时产生脏数据
            while (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "--->售出第:  " + tickets + " 票");
                tickets--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (tickets <= 0) {
                System.out.println(Thread.currentThread().getName() + "--->售票结束!");
            }
        }
    }


    public static void main(String[] args) {
        SellTickets sell = new ThreadUnSecurity().new SellTickets();

        Thread thread1 = new Thread(sell, "1号窗口");
        Thread thread2 = new Thread(sell, "2号窗口");
        Thread thread3 = new Thread(sell, "3号窗口");
        Thread thread4 = new Thread(sell, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

上述代码运行的结果:

1号窗口--->售出第:  10 票
4号窗口--->售出第:  10 票
2号窗口--->售出第:  10 票
3号窗口--->售出第:  10 票
4号窗口--->售出第:  6 票
1号窗口--->售出第:  5 票
2号窗口--->售出第:  4 票
3号窗口--->售出第:  6 票
3号窗口--->售出第:  2 票
4号窗口--->售出第:  1 票
1号窗口--->售票结束!
2号窗口--->售出第:  2 票
4号窗口--->售票结束!
2号窗口--->售票结束!
3号窗口--->售票结束!

Process finished with exit code 0

我们可以看出同一张票在不对票数进行保护时会出现同一张票会被出售多次!由于线程调度中的不确定性,读者在演示上述代码时,出现的运行结果会有不同。

第一种方式:同步代码块

package com.example.springbooxianchengchi.xcc;

public class ThreadSynchronizedSecurity {

    static int tickets = 10;

    class SellTickets implements Runnable {

        @Override
        public void run() {
            // 同步代码块
            while (tickets > 0) {
                synchronized (this) {
                    //System.out.println(this.getClass().getName().toString());
                    if (tickets <= 0) {
                        return;
                    }
                    System.out.println(Thread.currentThread().getName() + "--->售出第:  " + tickets + " 票");
                    tickets--;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (tickets <= 0) {
                    System.out.println(Thread.currentThread().getName() + "--->售票结束!");
                }
            }
        }
    }

    public static void main(String[] args) {
        SellTickets sell = new ThreadSynchronizedSecurity().new SellTickets();

        Thread thread1 = new Thread(sell, "1号窗口");
        Thread thread2 = new Thread(sell, "2号窗口");
        Thread thread3 = new Thread(sell, "3号窗口");
        Thread thread4 = new Thread(sell, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

上述代码运行的结果:

1号窗口--->售出第:  10 票
2号窗口--->售出第:  9 票
2号窗口--->售出第:  8 票
2号窗口--->售出第:  7 票
2号窗口--->售出第:  6 票
2号窗口--->售出第:  5 票
2号窗口--->售出第:  4 票
2号窗口--->售出第:  3 票
2号窗口--->售出第:  2 票
1号窗口--->售出第:  1 票
1号窗口--->售票结束!

Process finished with exit code 0

输出结果读者可自行调试,不会出现同一张票被出售多次的情况。

第二种方式:同步方法

package com.example.springbooxianchengchi.xcc;

public class ThreadSynchroniazedMethodSecurity {

    static int tickets = 10;

    class SellTickets implements Runnable {

        @Override
        public void run() {
            //同步方法
            while (tickets > 0) {
                synMethod();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (tickets <= 0) {
                    System.out.println(Thread.currentThread().getName() + "--->售票结束");
                }
            }
        }

        synchronized void synMethod() {
            synchronized (this) {
                if (tickets <= 0) {
                    return;
                }
                System.out.println(Thread.currentThread().getName() + "---->售出第 " + tickets + " 票 ");
                tickets--;
            }
        }
    }

    public static void main(String[] args) {
        SellTickets sell = new ThreadSynchroniazedMethodSecurity().new SellTickets();

        Thread thread1 = new Thread(sell, "1号窗口");
        Thread thread2 = new Thread(sell, "2号窗口");
        Thread thread3 = new Thread(sell, "3号窗口");
        Thread thread4 = new Thread(sell, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }

}

上述代码运行的结果:

1号窗口---->售出第 10 票 
2号窗口---->售出第 9 票 
3号窗口---->售出第 8 票 
4号窗口---->售出第 7 票 
3号窗口---->售出第 6 票 
4号窗口---->售出第 5 票 
1号窗口---->售出第 4 票 
2号窗口---->售出第 3 票 
4号窗口---->售出第 2 票 
1号窗口---->售出第 1 票 
2号窗口--->售票结束
1号窗口--->售票结束
4号窗口--->售票结束
3号窗口--->售票结束

Process finished with exit code 0

读者可自行调试上述代码的运行结果。

第三种方式:Lock锁机制

通过创建Lock对象,采用lock()加锁,unlock()解锁,来保护指定的代码块。

package com.example.springbooxianchengchi.xcc;

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

public class ThreadLockSecurity {

    static int tickets = 10;

    class SellTickets implements Runnable {

        Lock lock = new ReentrantLock();

        @Override
        public void run() {
            // Lock锁机制
            while (tickets > 0) {
                try {
                    lock.lock();
                    if (tickets <= 0) {
                        return;
                    }
                    System.out.println(Thread.currentThread().getName() + "--->售出第:  " + tickets + " 票");
                    tickets--;
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } finally {
                    lock.unlock();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (tickets <= 0) {
                System.out.println(Thread.currentThread().getName() + "--->售票结束!");
            }

        }
    }


    public static void main(String[] args) {
        SellTickets sell = new ThreadLockSecurity().new SellTickets();

        Thread thread1 = new Thread(sell, "1号窗口");
        Thread thread2 = new Thread(sell, "2号窗口");
        Thread thread3 = new Thread(sell, "3号窗口");
        Thread thread4 = new Thread(sell, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }

}

上述代码运行的结果:

1号窗口--->售出第:  10 票
2号窗口--->售出第:  9 票
3号窗口--->售出第:  8 票
4号窗口--->售出第:  7 票
4号窗口--->售出第:  6 票
1号窗口--->售出第:  5 票
2号窗口--->售出第:  4 票
3号窗口--->售出第:  3 票
2号窗口--->售出第:  2 票
3号窗口--->售出第:  1 票
3号窗口--->售票结束!
2号窗口--->售票结束!

Process finished with exit code 0

最后总结

由于synchronized是在JVM层面实现的,因此系统可以监控锁的释放与否;而ReentrantLock是使用代码实现的,系统无法自动释放锁,需要在代码中的finally子句中显式释放锁lock.unlock()。

另外,在并发量比较小的情况下,使用synchronized是个不错的选择;但是在并发量比较高的情况下,其性能下降会很严重,此时ReentrantLock是个不错的方案。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值