facebook twitter hatena line google mixi email

Android/排他制御

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

synchronizedブロック

-HaitaCommand.java

public class HaitaCommand {
   public void exec() {
       synchronized(this) {
           try {
               TimeUnit.SECONDS.sleep(3);
               Log.i("test", "haitaexec");
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }
   public void exec2() {
       synchronized(this) {
           try {
               TimeUnit.SECONDS.sleep(3);
               Log.i("test", "haitaexec2");
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }
}

-MainActivity.java

       final HaitaCommand command = new HaitaCommand();
       new Thread(new Runnable() {
           @Override
           public void run() {
               command.exec2();
           }
       }).start();
       command.exec();
       command.exec();

3秒ごとに処理された

12-20 11:02:06.623 2141-2141/com.example.test.myapplication I/test: haitaexec
12-20 11:02:09.633 2141-2141/com.example.test.myapplication I/test: haitaexec
12-20 11:02:12.723 2141-2432/com.example.test.myapplication I/test: haitaexec2

synchronizedメソッド

synchronized(this)と同じ挙動でロック単位はmethod単位でなくclass単位になる。

-HaitaCommand.java

public class HaitaCommand {
   public synchronized void exec() {
       try {
           TimeUnit.SECONDS.sleep(3);
           Log.i("test", "haitaexec");
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
   public synchronized void exec2() {
       try {
           TimeUnit.SECONDS.sleep(3);
           Log.i("test", "haitaexec2");
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}

-MainActivity.java

       final HaitaCommand command = new HaitaCommand();
       new Thread(new Runnable() {
           @Override
           public void run() {
               command.exec2();
           }
       }).start();
       command.exec();
       command.exec();

3秒ごとに処理された

12-20 11:00:23.143 32076-32076/com.example.test.myapplication I/test: haitaexec
12-20 11:00:26.143 32076-32076/com.example.test.myapplication I/test: haitaexec
12-20 11:00:29.183 32076-32424/com.example.test.myapplication I/test: haitaexec2