这里学习一下java多线程中的关于synchronized的用法。我来不及认真地年轻,待明白过来时,只能选择认真地老去。
synchronized的简单实例
一、 synchronized在方法上的使用
public class SynchronizedTest { public static void main(String[] args) { MyThreadB threadB = new MyThreadB(); new Thread(threadB, "T-1").start(); new Thread(threadB, "T-2").start(); } static class MyThreadB implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " before"); printString(); System.out.println(Thread.currentThread().getName() + " after"); } private synchronized void printString() { for (int i = 0; i < 3; i++) { try { TimeUnit.SECONDS.sleep(i + 1); System.out.println(Thread.currentThread().getName() + " , i = " + i); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
运行的一次结果如下:
T-1 before T-2 before T-1 , i = 0 T-1 , i = 1 T-1 , i = 2 T-1 after T-2 , i = 0 T-2 , i = 1 T-2 , i = 2 T-2 after
如果去掉synchronized之后,一次的打印结果如下:
T-1 before T-2 before T-1 , i = 0 T-2 , i = 0 T-1 , i = 1 T-2 , i = 1 T-1 , i = 2 T-1 after T-2 , i = 2 T-2 after
二、synchronized代码块的使用
public class SynchronizedTest { public static void main(String[] args) { MyThreadA threadA = new MyThreadA(); new Thread(threadA, "T-1").start(); new Thread(threadA, "T-2").start(); } static class MyThreadA implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " outside of synchronized."); synchronized (this) { for (int i = 0; i < 3; i++) { try { TimeUnit.SECONDS.sleep(i + 1); System.out.println(Thread.currentThread().getName() + " , i = " + i); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
一次的运行结果如下:
T-2 outside of synchronized. T-1 outside of synchronized. T-2 , i = 0 T-2 , i = 1 T-2 , i = 2 T-1 , i = 0 T-1 , i = 1 T-1 , i = 2
如果去掉synchronized之后,一次的打印结果如下:
T-1 outside of synchronized. T-2 outside of synchronized. T-2 , i = 0 T-1 , i = 0 T-2 , i = 1 T-1 , i = 1 T-1 , i = 2 T-2 , i = 2