Java本格入門 Chapter11 スレッドセーフをたしなむ の一部をJavaで実装。
Java本格入門 Chapter11 スレッドセーフをたしなむ の 11-2-3(1)異なるクラスのsynchronizedメソッドは、同期しない。を実装。
書籍の簡略コードではいまいち刺さらなかったので。
実装の参照元ネタ
こちらのサイト様のコードを写経させていただきました。abcdefg..... : Javaでsynchronizedの排他制御を試す
ファイル一覧
- MyMain.java
実装
MyMain.java
- public class MyMain {
- public static void main(String[] args) {
- MyMain aaa = new MyMain();
- aaa.test27();
- System.out.println("★★★★★");
- }
- // マルチスレッドでのsyncronized範囲確認
- private void test27() {
- final class AAA {
- public synchronized void func3() throws InterruptedException {
- System.out.println(Thread.currentThread().getName() + " : ★ start");
- Thread.sleep(2000);
- System.out.println(Thread.currentThread().getName() + " : ★ end");
- }
- public synchronized void func4() throws InterruptedException {
- System.out.println(Thread.currentThread().getName() + " : ○ start");
- Thread.sleep(2000);
- System.out.println(Thread.currentThread().getName() + " : ○ end");
- }
- }
- final class BBB {
- public synchronized void func3() throws InterruptedException {
- System.out.println(Thread.currentThread().getName() + " : ★★ start");
- Thread.sleep(2000);
- System.out.println(Thread.currentThread().getName() + " : ★★ end");
- }
- }
- AAA aaa = new AAA();
- Runnable r1 = () -> {
- try {
- aaa.func3();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- };
- Runnable r2 = () -> {
- try {
- aaa.func4();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- };
- BBB bbb = new BBB();
- Runnable r3 = () -> {
- try {
- bbb.func3();
- } catch ( InterruptedException e) {
- e.printStackTrace();
- }
- };
- new Thread(r1).start();
- new Thread(r2).start();
- new Thread(r3).start();
- }
出力結果
★★★★★ ← main()終了。Thread-2 : ★★ start ← 非同期
Thread-1 : ○ start ← 同期
Thread-2 : ★★ end ← 非同期
Thread-1 : ○ end ← 同期
Thread-0 : ★ start ← 同期
Thread-0 : ★ end ←同期
所感
まぁわかる。いつかこういう教本が、ソース共有だけじゃなくって、オンデマンドなテスト環境とかと連携して、もっと動かしたりできると良いですよね。AngularのStackBlitzみたいな。
コメント
コメントを投稿