Created
July 14, 2015 15:16
-
-
Save orekyuu/bc0c0d010dd9707a7790 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
| import java.util.concurrent.ExecutorService; | |
| import java.util.concurrent.Executors; | |
| public class Main { | |
| public static void main(String[] args) { | |
| System.setProperty("debug", "true"); | |
| ExecutorService service = Executors.newFixedThreadPool(4); | |
| Util util = new Util(2); | |
| service.submit(() -> { | |
| util.lockStart(2); | |
| System.out.println("A"); | |
| util.lockEnd(2); | |
| }); | |
| service.submit(() -> { | |
| util.lockStart(1); | |
| System.out.println("B"); | |
| util.lockEnd(1); | |
| }); | |
| try { | |
| //これどうしよう・・・ | |
| Thread.sleep(100); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| util.unlockOrder(); | |
| service.shutdown(); | |
| } | |
| } |
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
| public class Util { | |
| private static final boolean enable; | |
| static { | |
| enable = Boolean.valueOf(System.getProperty("debug", "false")); | |
| } | |
| private volatile Object[] lockObjects; | |
| public Util(int size) { | |
| lockObjects = new Object[size]; | |
| } | |
| public void lockStart(int seq) { | |
| if (!enable) return; | |
| lockObjects[seq - 1] = new Object(); | |
| synchronized (lockObjects[seq - 1]) { | |
| try { | |
| System.out.println("wait before: " + seq); | |
| lockObjects[seq - 1].wait(); | |
| System.out.println("wait after: " + seq); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| } | |
| public void lockEnd(int seq) { | |
| if (!enable) return; | |
| if (lockObjects.length != seq) { | |
| synchronized (lockObjects[seq]) { | |
| lockObjects[seq].notify(); | |
| } | |
| } | |
| } | |
| public void unlockOrder() { | |
| if (!enable) return; | |
| lockEnd(0); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment