Java 学习笔记之 线程安全
Posted AK47Sonic
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 学习笔记之 线程安全相关的知识,希望对你有一定的参考价值。
线程安全:
线程安全的方法一定是排队运行的。
public class SyncObject { synchronized public void methodA() { try { System.out.println("begin methodA threadName = " + Thread.currentThread().getName()); Thread.sleep(5000); System.out.println("end"); } catch (InterruptedException e) { e.printStackTrace(); } } } public class SyncThreadA extends Thread{ private SyncObject object; public SyncThreadA(SyncObject object) { this.object = object; } @Override public void run() { super.run(); object.methodA(); } } public class SyncThreadB extends Thread{ private SyncObject object; public SyncThreadB(SyncObject object) { this.object = object; } @Override public void run() { super.run(); object.methodA(); } } public class ThreadRunMain { public static void main(String[] args) { testSyncThread(); } public static void testSyncThread(){ SyncObject object = new SyncObject(); SyncThreadA a = new SyncThreadA(object); a.setName("A"); SyncThreadB b = new SyncThreadB(object); b.setName("B"); a.start(); b.start(); } }
运行结果:
如果去掉synchronized,运行结果:
以上是关于Java 学习笔记之 线程安全的主要内容,如果未能解决你的问题,请参考以下文章