Java本格入門 Chapter11 スレッドセーフをたしなむ の一部をJavaで実装。

Java本格入門 Chapter11 スレッドセーフをたしなむ の 11-2-3(1)異なるクラスのsynchronizedメソッドは、同期しない。を実装。

書籍の簡略コードではいまいち刺さらなかったので。

実装の参照元ネタ

こちらのサイト様のコードを写経させていただきました。
abcdefg..... : Javaでsynchronizedの排他制御を試す

ファイル一覧

  1. MyMain.java

実装


MyMain.java


  1. public class MyMain {
  2. public static void main(String[] args) {
  3. MyMain aaa = new MyMain();
  4. aaa.test27();
  5. System.out.println("★★★★★");
  6. }
  7.  
  8. // マルチスレッドでのsyncronized範囲確認
  9. private void test27() {
  10. final class AAA {
  11. public synchronized void func3() throws InterruptedException {
  12. System.out.println(Thread.currentThread().getName() + " : ★ start");
  13. Thread.sleep(2000);
  14. System.out.println(Thread.currentThread().getName() + " : ★ end");
  15. }
  16.  
  17. public synchronized void func4() throws InterruptedException {
  18. System.out.println(Thread.currentThread().getName() + " : ○ start");
  19. Thread.sleep(2000);
  20. System.out.println(Thread.currentThread().getName() + " : ○ end");
  21. }
  22. }
  23.  
  24. final class BBB {
  25. public synchronized void func3() throws InterruptedException {
  26. System.out.println(Thread.currentThread().getName() + " : ★★ start");
  27. Thread.sleep(2000);
  28. System.out.println(Thread.currentThread().getName() + " : ★★ end");
  29. }
  30. }
  31.  
  32. AAA aaa = new AAA();
  33. Runnable r1 = () -> {
  34. try {
  35. aaa.func3();
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. };
  40. Runnable r2 = () -> {
  41. try {
  42. aaa.func4();
  43. } catch (InterruptedException e) {
  44. e.printStackTrace();
  45. }
  46. };
  47.  
  48. BBB bbb = new BBB();
  49. Runnable r3 = () -> {
  50. try {
  51. bbb.func3();
  52. } catch ( InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. };
  56.  
  57. new Thread(r1).start();
  58. new Thread(r2).start();
  59. new Thread(r3).start();
  60. }

出力結果

★★★★★ ← main()終了。
Thread-2 : ★★ start ← 非同期
Thread-1 : ○ start ← 同期
Thread-2 : ★★ end ← 非同期
Thread-1 : ○ end ← 同期
Thread-0 : ★ start ← 同期
Thread-0 : ★ end ←同期

所感

まぁわかる。
いつかこういう教本が、ソース共有だけじゃなくって、オンデマンドなテスト環境とかと連携して、もっと動かしたりできると良いですよね。AngularのStackBlitzみたいな。

コメント

このブログの人気の投稿

windows10 で nvidia のグラボのcode43現象を解決した

Java : processbuilder 標準出力 タイムアウト

GTX560Ti がおかしい(code 43が出る)(2018年)→解決しました(2019)