重学JAVA基础(六):多线程的同步
1.synchronized关键字
/** * 同步关键字 * @author tomsnail * @date 2015年4月18日 下午12:12:39 */ public class SyncThreadTest { private static final byte[] lock = new byte[1]; /** * 同步方法 * @author tomsnail * @date 2015年4月18日 下午12:15:30 */ public synchronized void test1(){ } /** * 同步块 * @author tomsnail * @date 2015年4月18日 下午12:15:17 */ public void test2(){ synchronized (lock) { } } }
2.volatile关键字
/** * volatile关键字 * @author tomsnail * @date 2015年4月18日 下午12:21:58 */ public class VolatileThreadTest { private volatile int count = 100; public void add(int number){ count+=number; } public int getCount(){ return count; } }
3.Lock锁
/** * lock锁 * @author tomsnail * @date 2015年4月18日 下午12:58:49 */ public class LockThreadTest { private Lock lock = new ReentrantLock(); private int count = 100; public void test(){ lock.lock(); count++; System.out.println(count); lock.unlock(); } }
4.Mutex信号量
/** * 线程信号量 * @author tomsnail * @date 2015年4月18日 下午1:14:47 */ public class MutexThreadTest { private CountDownLatch countDownLatch = new CountDownLatch(1); private Semaphore s = new Semaphore(5); public void a(){ try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } public void b(){ countDownLatch.countDown(); } public void c(){ try { System.out.println(" try acquire s"); s.acquire(); System.out.println(" acquire s"); } catch (InterruptedException e) { e.printStackTrace(); } } public void d(){ s.release(); System.out.println(" release s"); } public static void main(String[] args) { MutexThreadTest mutexThreadTest = new MutexThreadTest(); for(int i=0;i<10;i++){ new Thread(new ThreadTest(mutexThreadTest)).start(); } mutexThreadTest.a(); System.out.println("a..."); for(int i=0;i<10;i++){ new Thread(new ThreadTest2(mutexThreadTest)).start(); } } } class ThreadTest implements Runnable{ private MutexThreadTest mutexThreadTest; public ThreadTest(MutexThreadTest mutexThreadTest){ this.mutexThreadTest = mutexThreadTest; } @Override public void run() { try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("mutexThreadTest countDown"); mutexThreadTest.b(); } } class ThreadTest2 implements Runnable{ private MutexThreadTest mutexThreadTest; public ThreadTest2(MutexThreadTest mutexThreadTest){ this.mutexThreadTest = mutexThreadTest; } @Override public void run() { mutexThreadTest.c(); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } mutexThreadTest.d(); } }