java 线程安全 synchronized
一、同步代码块
1、格式
synchronized (锁对象/任意对象){ // 涉及安全的代码 }
2、案例(买票问题)
package com.wt.synchronize; public class Demon01Syn implements Runnable { public int tick =100; Object ob = new Object(); @Override public void run() { while (true){ try { Thread.sleep(1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } synchronized (ob){ if (tick>0){ System.out.println(Thread.currentThread().getName()+":购买第"+tick+"张票"); tick--; }else { break; } } } } }
package com.wt.synchronize; public class Demon01 { public static void main(String[] args) { Demon01Syn syn = new Demon01Syn(); Thread thread = new Thread(syn, "小明"); Thread thread1 = new Thread(syn, "小红"); Thread thread2 = new Thread(syn, "小李"); // 开启 thread.start(); thread1.start(); thread2.start(); } }
二、同步方法
1、非静态方法,锁是this
a、格式
修饰符 synchronized 类型 方法名(参数){ 安全代码; return }
b、案例
package com.wt.synchronize; public class Demon02Syn implements Runnable{ public int tick = 100; @Override public void run() { while (true){ method(); if (tick==0){ break; } } } public synchronized void method(){ //安全 if (tick>0){ System.out.println(Thread.currentThread().getName()+"购买了第"+tick+"张票"); this.tick--; } } }
package com.wt.synchronize; public class Demon02 { public static void main(String[] args) { Demon02Syn demon02Syn = new Demon02Syn(); Thread thread = new Thread(demon02Syn, "小红"); Thread thread1 = new Thread(demon02Syn, "小蓝"); Thread thread2 = new Thread(demon02Syn, "小明"); // 开启 thread.start(); thread1.start(); thread2.start(); } }
2、静态方法,锁是class
a、格式
修饰符 static synchronized 类型 方法名(参数){ 安全代码; return }
b、案例
package com.wt.synchronize; public class Demon03Syn implements Runnable{ public static int tick = 50; @Override public void run() { try { Thread.sleep(100L); } catch (InterruptedException e) { throw new RuntimeException(e); } while (tick>1){ method(); } } public static synchronized void method(){ System.out.println(Thread.currentThread().getName()+"购买"+tick); tick--; } }
package com.wt.synchronize; public class Demon03 { public static void main(String[] args) { Demon03Syn demon03Syn = new Demon03Syn(); Thread a = new Thread(demon03Syn, "A"); Thread b = new Thread(demon03Syn, "B"); Thread c = new Thread(demon03Syn, "C"); b.start(); c.start(); a.start(); } }