标签:
/* 线程同步 * 1、同步代码块 2、同步方法 3、Lock * */ import java.util.concurrent.locks.ReentrantLock; public class Thread03 { public static void main(String[] args) { Runnable r1 = new MyRunnable(); Thread t1 = new Thread(r1); Thread t2 = new Thread(r1); t1.start(); t2.start(); } } class MyRunnable implements Runnable { private int flag; @Override public void run() { this.compose();// 不能达到预期的0->1... // 同步代码块 // this.synchronizedCodeBlockMethod(); // 同步方法 // this.synchronizedMethod(); // 互斥锁 // this.reentrantLockMethod(); } // 同步代码块 private Object obj = new Object(); public void synchronizedCodeBlockMethod() { synchronized (obj) { this.compose(); } } // 同步方法 public synchronized void synchronizedMethod() { this.compose(); } // 互斥锁 private final ReentrantLock lock = new ReentrantLock(); public void reentrantLockMethod() { this.lock.lock(); this.compose(); this.lock.unlock(); } public void compose() { for (int i = 0; i < 5; i++) { this.flag = 0; System.out.println("程序开始-" + this.flag); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } this.flag = 1; System.out.println("程序结束-" + this.flag); } } }
标签:
原文地址:http://www.cnblogs.com/xiaowangzhi/p/5677212.html