Android/排他制御
提供: 初心者エンジニアの簡易メモ
2016年12月20日 (火) 11:33時点におけるAdmin (トーク | 投稿記録)による版 (ページの作成:「==synchronizedメソッド== -HaitaCommand.java public class HaitaCommand { public synchronized void exec() { try { TimeUnit.SECONDS.sleep(3);...」)
synchronizedメソッド
-HaitaCommand.java
public class HaitaCommand {
public synchronized void exec() {
try {
TimeUnit.SECONDS.sleep(3);
Log.i("test", "haitaexec");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
-MainActivity.java
(new HaitaCommand()).exec();
(new HaitaCommand()).exec();
new Thread(new Runnable() {
@Override
public void run() {
(new HaitaCommand()).exec();
}
}).start();
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: haitaexec
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();
}
}
}
}
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: haitaexec
