「Android/排他制御」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→synchronizedメソッド) |
(→synchronizedブロック) |
||
| 行40: | 行40: | ||
public class HaitaCommand { | public class HaitaCommand { | ||
public void exec() { | public void exec() { | ||
| + | synchronized(this) { | ||
| + | try { | ||
| + | TimeUnit.SECONDS.sleep(3); | ||
| + | Log.i("test", "haitaexec"); | ||
| + | } catch (InterruptedException e) { | ||
| + | e.printStackTrace(); | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | public void exec2() { | ||
synchronized(this) { | synchronized(this) { | ||
try { | try { | ||
| 行53: | 行63: | ||
12-20 11:02:06.623 2141-2141/com.example.test.myapplication I/test: haitaexec | 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: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: | + | 12-20 11:02:12.723 2141-2432/com.example.test.myapplication I/test: haitaexec2 |
2016年12月20日 (火) 11:42時点における版
synchronizedメソッド
-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", "haitaexec");
} 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
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", "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: haitaexec2
