线程安全问题

当多个线程同时共享,同一个全局变量或静态变量,做写的操作时,可能会发生数据冲突问题,也就是线程安全问题。但是做读操作是不会发生数据冲突问题。

案例:需求现在有100张火车票,有两个窗口同时抢火车票,请使用多线程模拟抢票效果。

代码:

package com.jvm.test;

class ThreadTrain1 implements Runnable {
    private int count = 100;
    private Object oj = new Object();

    @Override
    public void run() {
        while (count > 0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                // TODO: handle exception
            }
            sale();
        }
    }

    public void sale() {
        // 前提 多线程进行使用、多个线程只能拿到一把锁。
        // 保证只能让一个线程 在执行 缺点效率降低
        // synchronized (oj) {
//		if (count > 0) {
        System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "票");
        count--;
//		}
        // }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        ThreadTrain1 threadTrain1 = new ThreadTrain1();
        Thread t1 = new Thread(threadTrain1, "①号窗口");
        Thread t2 = new Thread(threadTrain1, "②号窗口");
        t1.start();
        t2.start();
    }
}

运行结果:

①号窗口和②号窗口同时出售火车第1张和第5张,部分火车票会重复出售。

结论发现,多个线程共享同一个全局成员变量时,做写的操作可能会发生数据冲突问题。

多个线程共享一个局部变量,做写操作,不会发生线程安全问题

 

线程安全的解决办法

一、同步代码块

对象如同锁,持有锁的线程可以在同步中执行 

没持有锁的线程即使获取CPU的执行权,也进不去 

同步的前提: 

1,必须要有两个或者两个以上的线程 

2,必须是多个线程使用同一个锁 

3,必须保证同步中只能有一个线程在运行 

 

好处:解决了多线程的安全问题 

弊端:多个线程需要判断锁,较为消耗资源、抢锁的资源。 

 

二、同步函数

在方法上修饰synchronized 称为同步函数

注意:同步函数其实就是使用的 this 锁,他们属于同一把锁

证明方法:

package com.jvm.test;

class ThreadTrain2 implements Runnable {
    private int count = 100;
    public boolean flag = true;
    private object oj = new Object();

    @Override
    public void run() {
        if (flag) {

            while (count > 0) {

                synchronized (this) {
                    if (count > 0) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "票");
                        count--;
                    }
                }

            }

        } else {
            while (count > 0) {
                sale();
            }
        }

    }

    public synchronized void sale() {
        // 前提 多线程进行使用、多个线程只能拿到一把锁。
        // 保证只能让一个线程 在执行 缺点效率降低
        // synchronized (oj) {
        if (count > 0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "票");
            count--;
        }
        // }
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) throws InterruptedException {
        ThreadTrain2 threadTrain1 = new ThreadTrain2();
        Thread t1 = new Thread(threadTrain1, "①号窗口");
        Thread t2 = new Thread(threadTrain1, "②号窗口");
        t1.start();
        Thread.sleep(40);
        threadTrain1.flag = false;
        t2.start();
    }
}

运行结果线程安全:

如果将上面的代码中 this锁改成oj锁,再运行:

三、静态同步函数

方法上加上static关键字,使用synchronized 关键字修饰 或者使用类.class文件。

注意:静态的同步函数使用的锁是  该函数所属字节码文件对象

可以用 getClass方法获取,也可以用当前  类名.class 表示。

证明方法:

class ThreadTrain2 implements Runnable {
    private static int count = 100;
    public boolean flag = true;
    private Object oj = new Object();

    @Override
    public void run() {
        if (flag) {

            while (count > 0) {

                synchronized (ThreadTrain2.class) {
                    if (count > 0) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "票");
                        count--;
                    }
                }

            }

        } else {
            while (count > 0) {
                sale();
            }
        }

    }

    public static synchronized void sale() {
        // 前提 多线程进行使用、多个线程只能拿到一把锁。
        // 保证只能让一个线程 在执行 缺点效率降低
        // synchronized (oj) {
        if (count > 0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "票");
            count--;
        }
        // }
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) throws InterruptedException {
        ThreadTrain2 threadTrain1 = new ThreadTrain2();
        Thread t1 = new Thread(threadTrain1, "①号窗口");
        Thread t2 = new Thread(threadTrain1, "②号窗口");
        t1.start();
        Thread.sleep(40);
        threadTrain1.flag = false;
        t2.start();
    }
}

运行结果线程安全:

如果将上面的代码中 ThreadTrain2.class 改成oj锁,再运行:

 

总结:

synchronized 修饰方法使用锁是当前this锁。

synchronized 修饰静态方法使用锁是当前类的字节码文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值