java 多线程:Thread 并发线程: 方法同步synchronized关键字,与static的结合
1、方法内的变量是安全的
方法内定义的变量,每个变量对应单独的内存变量地址,多个线程之间相互不影响。多个线程之间的变量根本没有一毛钱关系
public class ThreadFuncVarSafe { public static void main(String[] args) { Runnable r = () -> { String tmp ; String currentThreadName = Thread.currentThread().getName(); if("A".equals(currentThreadName)){ tmp = "I am A"; }else { tmp = "I am B"; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread Name:" + currentThreadName + ", func_var is:" + tmp); }; Thread threadA = new Thread(r,"A"); Thread threadB = new Thread(r,"B"); threadA.start(); threadB.start(); } }
2、实体变量线程不安全
/** * @ClassName ThreadsClassVarNotSafe * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/22. */ public class ThreadsClassVarNotSafe { private static class MyRunnable implements Runnable{ private String tmp; @Override public void run() { String currentThreadName = Thread.currentThread().getName(); if("A".equals(currentThreadName)){ tmp = "I am A"; }else { tmp = "I am B"; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread Name:" + currentThreadName + ", func_var is:" + tmp); } } public static void main(String[] args) { Runnable r = new MyRunnable(); Thread threadA = new Thread(r,"A"); //同一个实体对象,最后输出被后执行的覆盖两个线程最后输出的结果一样都为A,或者都为B Thread threadB = new Thread(r,"B"); //同一个实体对象,最后输出被后执行的覆盖两个线程最后输出的结果一样都为A,或者都为B // Thread threadA = new Thread(new MyRunnable(),"A");//这种是不同的实体对象,相互无影响 // Thread threadB = new Thread(new MyRunnable(),"B");//这种是不同的实体对象,相互无影响 threadA.start(); threadB.start(); } }
...方法安全...
3、方法用synchronized关键字修饰方法(方法安全),多线程遇到同一个对象的该方法变串行
同一个实体对象,对实体的方法加锁,多个线程调用同一个实体对象的 安全方法
/** * @ClassName ThreadsClassVarNotSafe * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/22. */ public class ThreadsFuncSafe { private static class MyRunnable implements Runnable{ private String tmp; @Override public synchronized void run() { String currentThreadName = Thread.currentThread().getName(); if("A".equals(currentThreadName)){ tmp = "I am A"; }else { tmp = "I am B"; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread Name:" + currentThreadName + ", func_var is:" + tmp); } } public static void main(String[] args) { Runnable r = new MyRunnable(); Thread threadA = new Thread(r,"A"); //同一个实体对象,MyRunnable类run方法被synchronized修饰,只能一个线程持有run()方法执行权限,两个线程运行到run()变串行 Thread threadB = new Thread(r,"B"); //同一个实体对象,MyRunnable类run方法被synchronized修饰,只能一个线程持有run()方法执行权限,两个线程运行到run()变串行 threadA.start(); threadB.start(); } }
4、多个实例多个锁,每个实例独立变量对象互不影响;实例外变量则有影响
示例:1、每个实例独立变量对象互不影响
/** * @ClassName ThreadsClassVarNotSafe * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/22. */ public class ThreadsMultiObjectVarSafe { private static class MyRunnable implements Runnable{ private String tmp; @Override public void run() { String currentThreadName = Thread.currentThread().getName(); if("A".equals(currentThreadName)){ tmp = "I am A"; }else { tmp = "I am B"; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread Name:" + currentThreadName + ", func_var is:" + tmp); } } public static void main(String[] args) { Thread threadA = new Thread(new MyRunnable(),"A"); //不同实体对象,方法无synchronized,变量独立互不影响 Thread threadB = new Thread(new MyRunnable(),"B"); //不同实体对象,方法无synchronized,变量独立互不影响 threadA.start(); threadB.start(); } }
示例:2、多个线程实例修改实例外变量,不安全
import java.util.HashSet; import java.util.Set; /** * @ClassName ThreadsMultiObjectOutofVarNotSafe * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/22. */ public class ThreadsMultiObjectOutofVarNotSafe { private static int num = 0; private static class MyThread extends Thread{ @Override public synchronized void run() { for (int i=0; i<100000; i++){ num ++; } System.out.println(getName() + "num:" + num); } } public static void main(String[] args) { Set<MyThread> threads = new HashSet<>(); for (int i=0; i<5; i++){ threads.add(new MyThread()); } threads.forEach(thread ->thread.start()); /** * 等待子线程结束再从main中获取num看值多少 */ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main 线程中 sum最终为:" + num); //不足50万 } }
运行结果,我们就算加上了synchronized关键字之后,结果依然可能会出现不正确,那是因为我们创建了5个实例,我们的synchronized会锁住当前的对象实例,而我们现在有5个实例,所以,我们多个线程的run方法不会被synchronized相互锁上,所以结果不正确。
5、同步synchronized静态static方法多实例之间安全
示例:多个线程对象调用同一个类实现的对象 的 synchronized修饰的静态static方法。被锁住的对象变为当前的类,而非对象,所以多个线程遇到此类方法顺序进行。
import java.util.HashSet; import java.util.Set; /** * @ClassName ThreadsMultiObjectOutofVarNotSafe * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/22. */ public class ThreadsMultiObjectStaticFuncSyncSafe { private static int num = 0; private static class MyThread extends Thread{ private static synchronized void safeRun(){ for (int i=0; i<100000; i++){ num ++; } System.out.println(Thread.currentThread().getName() + " num:" + num); } @Override public void run() { safeRun(); } } public static void main(String[] args) { Set<MyThread> threads = new HashSet<>(); for (int i=0; i<5; i++){ threads.add(new MyThread()); } threads.forEach(thread ->thread.start()); /** * 等待子线程结束再从main中获取num看值多少 */ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main 线程中 sum最终为:" + num); //不足50万 } }
每次的结果都是正确的,是500000,这个是为什么?
因为,我们在static的方法上面加上synchronized之后,锁的钥匙就变成了当前对象的Class属性(MimlThread.class)。class属性在java里面是一个元数据,元数据在JVM中只保存了一份,所以我们对这个class上锁之后,不同的线程调用,会被相互排斥。
6,异常发生的时候,锁会自动释放
如上代码safeRun()方法中num++上抛出异常,不影响其他线程运行。
if(i >9){throw new RuntimeException();} //测试抛出异常后,是否影响其他线程,结果为 main 线程中 sum最终为:50 num ++;
posted on 2021-04-22 13:36 zhangmingda 阅读(378) 评论(0) 编辑 收藏 举报