synchronized的线程安全实现

百度百科:
       synchronized 关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法(或者该类的其他同步方法),有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。它包括两种用法:synchronized 方法和 synchronized 块。
      Java语言的关键字,可用来给对象和方法或者代码块加锁,当它锁定一个方法或者一个代码块的时候,同一时刻最多只有一个线程执行这段代码。当两个并发线程访问同一个对象object中的这个加锁同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。然而,当一个线程访问object的一个加锁代码块时,另一个线程仍可以访问该object中的非加锁代码块。

保证修饰的方法或代码块在多线程环境下只有一个线程获取锁进行访问,即能够保证在同一时刻最多只有一个线程执行该段代码,以达到保证并发安全的效果

用法分为两个:对象锁和类锁

修饰位置修饰类型加锁的对象举例备注
方法实例方法(非静态方法)类的实例对象(对象锁)public synchronized void method(){}非静态方法可以访问类的静态成员,也可以访问类的非静态成员
静态方法类对象(类锁)public synchronized void method(){}静态方法只能访问类的静态成员,不能访问类的非静态成员,静态方法既可以用实例来调用,也可以用类名来调用
代码块实例对象(调用该代码块的实例对象)类的实例对象(对象锁)synchronized(this){}对于对象锁来说,要保证作为锁的对象为同一个才能达到并发控制共享资源的作用
class对象类对象(类锁)sychronized(Sington.class){}对于类锁来说,所有对象共用同一把锁。且要保证多个线程下访问的类的类型一致,例如实现Runnable的类的实例,作为Thread类构造函数参数实例化线程对象时要保证该实例为同一个
任意实例对象实例对象(对象锁)Object o = new Object(); synchronized(o){}每个实例都对应有自己的一把锁,不同实例之间互不影响

三个线程打印轮流ABC5次

定义Lock类,将其实例作为对象锁

package MyThread;


/**
 * @author dustdawn
 * @date 2019/9/20 14:31
 */
public class ABCThread extends Thread {
    private Lock lock;
    private String flag;
    public ABCThread(String flag, Lock lock) {
        this.flag = flag;
        this.lock = lock;
    }
    @Override
    public void run() {
        int count = 5;
        //System.out.println(Thread.currentThread().getName()+"线程启动");
        while (count > 0) {
            synchronized (lock) {
                if (lock.getFlag().equals(flag)) {
                    System.out.print(flag);
                    count--;

                    if("A".equals(flag))
                        lock.setFlag("B");
                    else if("B".equals(flag))
                        lock.setFlag("C");
                    else if("C".equals(flag))
                        lock.setFlag("A");
                }
            }
        }

    }

    public static void main(String[] args) {
        Lock lock = new Lock();
        lock.setFlag("A");
        ABCThread thread1 = new ABCThread("A", lock);
        ABCThread thread2 = new ABCThread("B", lock);
        ABCThread thread3 = new ABCThread("C", lock);

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class Lock
{
    private String flag;

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public String getFlag() {
        return flag;
    }
}

每个线程执行同步代码块时,打印后通过修改if条件,使当前执行的线程跳出同步代码块,释放对象锁,其他线程进入获得锁同步代码块,随后重复操作。

多线程下共享数据并发安全实现

package MyThread;
/**
 * @author dustdawn
 * @date 2019/9/20 14:07
 */
class myThread implements Runnable{
    static int num = 0;
    static Integer a = 0;
    @Override
    public void run() {
            try {
                int threadId = Integer.parseInt(Thread.currentThread().getName());
                System.out.println("线程"+ threadId +"启动");
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        num++;
                        System.out.println("线程"+Thread.currentThread().getName() + ": num=" + num);
                        Thread.sleep(2000);
                        System.out.println("当前线程"+threadId+"唤醒阻塞线程了");
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();}
        }
    }
}
public class Main{
    public static void main(String[] args) {
        myThread m = new myThread();
        Thread t1 = new Thread(m, "1");
        Thread t2 = new Thread(m, "2");
        t1.start();
        t2.start();
    }
}

在这里插入图片描述

结果如上图所示,出现了线程不同步的情况

通过加synchronized同步代码块

通过类的实例对象加锁:

package MyThread;

/**
 * @author dustdawn
 * @date 2019/9/20 14:07
 */
class myThread implements Runnable{
    static int num = 0;
    static Integer a = 0;
    @Override
    public void run() {
        synchronized (this) {
            try {
                int threadId = Integer.parseInt(Thread.currentThread().getName());
                System.out.println("线程"+ threadId +"启动");
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        num++;
                        System.out.println("线程"+Thread.currentThread().getName() + ": num=" + num);
                        Thread.sleep(2000);
                        System.out.println("当前线程"+threadId+"唤醒阻塞线程了");
                        notify();
                    }else {
                        System.out.println("线程"+threadId+"要阻塞了");
                        wait();
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();}
        }
    }
}
public class Main{
    public static void main(String[] args) {
        myThread m = new myThread();
        Thread t1 = new Thread(m, "1");
        Thread t2 = new Thread(m, "2");
        t1.start();
        t2.start();
    }
}

通过任意实例对象的对象锁

package MyThread;

/**
 * @author dustdawn
 * @date 2019/9/20 14:07
 */

class myThread implements Runnable{
    static int num = 0;
    static Integer a = 0;
    @Override
    public void run() {
        synchronized (a) {
            try {
                int threadId = Integer.parseInt(Thread.currentThread().getName());
                System.out.println("线程"+ threadId +"启动");
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        num++;
                        System.out.println("线程"+Thread.currentThread().getName() + ": num=" + num);
                        Thread.sleep(2000);
                        System.out.println("当前线程"+threadId+"唤醒阻塞线程了");
                        a.notify();
                    }else {
                        System.out.println("线程"+threadId+"要阻塞了");
                        a.wait();
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();}
        }
    }


}
public class Main{
    public static void main(String[] args) {
        myThread m = new myThread();
        Thread t1 = new Thread(m, "1");
        Thread t2 = new Thread(m, "2");
        t1.start();
        t2.start();
    }
}

在这里插入图片描述

三个线程轮流打印A到Z

package MyThread;

/**
 * @author dustdawn
 * @date 2019/9/20 14:07
 */
class myThread implements Runnable{
    static int num = 0;
    static Integer a = 0;
    @Override
    public void run() {
        synchronized (a) {
            try {
                int threadId = Integer.parseInt(Thread.currentThread().getName());
                System.out.println("线程"+ threadId +"启动");
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        num++;
                        System.out.println("线程"+Thread.currentThread().getName() + ": num=" + num);
                        Thread.sleep(2000);
                        System.out.println("当前线程"+threadId+"唤醒阻塞线程了");
                        a.notify();
                    }else {
                        System.out.println("线程"+threadId+"要阻塞了");
                        a.wait();
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();}
        }
    }
}
public class Main{
    public static void main(String[] args) {
        myThread m = new myThread();
        Thread t1 = new Thread(m, "1");
        Thread t2 = new Thread(m, "2");
        t1.start();
        t2.start();
    }
}

在这里插入图片描述

用五个线程,顺序打印数字1~无穷大,其中每5个数字为1组

package MyThread;

/**
 * @author dustdawn
 * @date 2019/9/20 16:13
 * 一个多线程的问题,用五个线程,顺序打印数字1~无穷大,其中每5个数字为1组
 */
public class forCharacter2 {
    private static volatile int orderNum = 1;
    private static Object o = new Object();

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                synchronized (o) {
                    try {
                        int threadId = Integer.parseInt(Thread.currentThread().getName());
                        System.out.println("线程"+Thread.currentThread().getName()+"启动");
                        while (true) {
                            if (orderNum % 5 == threadId || orderNum % 5 == 0) {
                                if (orderNum % 5 == threadId) {//1-4
                                    System.out.println("线程" + threadId + ":" + orderNum++);
                                } else {
                                    System.out.println("线程" + 5 + ":" + orderNum++);
                                }
                                Thread.sleep(2000);
                                System.out.println("当前线程"+threadId+"唤醒阻塞线程了");
                                o.notifyAll();
                            } else {
                                //orderNum与thread不对应就阻塞
                                System.out.println("线程"+threadId+"要阻塞了,释放对象锁");
                                o.wait();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread t1 = new Thread(r, "1");
        Thread t2 = new Thread(r, "2");
        Thread t3 = new Thread(r, "3");
        Thread t4 = new Thread(r, "4");
        Thread t5 = new Thread(r, "5");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值