public class SynchronizeCodeBlockLock implements Runnable { private static SynchronizeCodeBlockLock instance = new SynchronizeCodeBlockLock(); private static int count = 0; @Override public void run() { method(); } private void method() { // 关键:同步代码块的方式,操作同一变量,达到线程安全的效果 synchronized (this) { System.out.println("线程名:" Thread.currentThread().getName() ",运行开始"); for (int i = 0; i < 10000; i ) { count ; } System.out.println("线程:" Thread.currentThread().getName() ",运行结束"); } } public static void main(String[] args) { Thread thread1 = new Thread(instance); Thread thread2 = new Thread(instance); thread1.start(); thread2.start(); while (thread1.isAlive() || thread2.isAlive()) { // 若有线程如果还在活动,则不执行下一步(等同于thread.join()方法) } System.out.println("期待结果:20000,实际结果:" count); } }
线程名:Thread-0,运行开始 线程:Thread-0,运行结束 线程名:Thread-1,运行开始 线程:Thread-1,运行结束 期待结果:20000,实际结果:20000
public class MethodLock implements Runnable { private static MethodLock instance = new MethodLock(); @Override public void run() { method(); } //关键:synchronized可以保证此方法被顺序执行,线程1执行完4秒钟后,线程2再执行4秒。不加synchronized,线程1和线程2将同时执行 private synchronized void method() { System.out.println("线程:" Thread.currentThread().getName() ",运行开始"); try { //模拟执行一段操作,耗时4秒钟 Thread.sleep(4000); System.out.println("线程:" Thread.currentThread().getName() ",运行结束"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { // 模拟:同一个对象下,两个线程,同步执行一个方法(串行执行则为线程安全,并行执行,则为线程不安全,) Thread thread1 = new Thread(instance); Thread thread2 = new Thread(instance); thread1.start(); thread2.start(); while (thread1.isAlive() || thread2.isAlive()) { } System.out.println("测试结束"); } }
线程:Thread-0,运行开始 线程:Thread-0,运行结束 线程:Thread-1,运行开始 线程:Thread-1,运行结束 测试结束
synchronized (共享变量) { //需要同步的代码 }
private synchronized void method() { //需要同步的代码 }