Created
April 24, 2014 10:16
-
-
Save arsenikt/11249274 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.cdzlab.locks; | |
| /** | |
| * @author arsenik | |
| */ | |
| public class LockTester { | |
| public LockTester() { | |
| } | |
| public void test() throws InterruptedException { | |
| Object a = new Object(); | |
| Object b = new Object(); | |
| Thread t1 = new Thread(new WorkTask(a, b), "1"); | |
| Thread t2 = new Thread(new WorkTask(a, b), "2"); | |
| t1.start(); | |
| t2.start(); | |
| Thread lockGuard = new Thread(new LockGuard(b), "lockGuard"); | |
| lockGuard.start(); | |
| } | |
| class LockGuard implements Runnable { | |
| private Object b; | |
| LockGuard(Object objB) { | |
| this.b = objB; | |
| } | |
| @Override | |
| public void run() { | |
| while (true) { | |
| guardNotify(); | |
| } | |
| } | |
| private void guardNotify() { | |
| try { | |
| Thread.sleep(3000); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| synchronized (b) { | |
| log(Thread.currentThread().getName(), "guard notify"); | |
| b.notify(); | |
| } | |
| } | |
| } | |
| class WorkTask implements Runnable { | |
| private Object a; | |
| private Object b; | |
| WorkTask(Object objA, Object objB) { | |
| this.a = objA; | |
| this.b = objB; | |
| } | |
| private void callMe(String name) throws InterruptedException { | |
| synchronized (a) { | |
| log(name, "a lock"); | |
| log(name, "get information"); | |
| work(); | |
| synchronized (b) { | |
| log(name, " b lock"); | |
| work(); | |
| b.wait(); | |
| log(name, " send information"); | |
| } | |
| } | |
| log(name, " after UI update"); | |
| } | |
| private void work() { | |
| try { | |
| Thread.sleep(1000); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| @Override | |
| public void run() { | |
| try { | |
| callMe(Thread.currentThread().getName()); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| } | |
| private void log(String name, String str) { | |
| System.out.println("[" + name + "] " + str); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment