「Android/排他制御」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==synchronizedメソッド== -HaitaCommand.java public class HaitaCommand { public synchronized void exec() { try { TimeUnit.SECONDS.sleep(3);...」) |
(→synchronizedメソッド) |
||
行3: | 行3: | ||
public class HaitaCommand { | public class HaitaCommand { | ||
public synchronized void exec() { | public synchronized void exec() { | ||
+ | try { | ||
+ | TimeUnit.SECONDS.sleep(3); | ||
+ | Log.i("test", "haitaexec"); | ||
+ | } catch (InterruptedException e) { | ||
+ | e.printStackTrace(); | ||
+ | } | ||
+ | } | ||
+ | public synchronized void exec2() { | ||
try { | try { | ||
TimeUnit.SECONDS.sleep(3); | TimeUnit.SECONDS.sleep(3); | ||
行13: | 行21: | ||
-MainActivity.java | -MainActivity.java | ||
− | + | final HaitaCommand command = new HaitaCommand(); | |
− | + | ||
new Thread(new Runnable() { | new Thread(new Runnable() { | ||
@Override | @Override | ||
public void run() { | public void run() { | ||
− | + | command.exec2(); | |
} | } | ||
}).start(); | }).start(); | ||
+ | command.exec(); | ||
+ | command.exec(); | ||
3秒ごとに処理された | 3秒ごとに処理された | ||
12-20 11:00:23.143 32076-32076/com.example.test.myapplication I/test: haitaexec | 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: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: | + | 12-20 11:00:29.183 32076-32424/com.example.test.myapplication I/test: haitaexec2 |
==synchronizedブロック== | ==synchronizedブロック== |
2016年12月20日 (火) 11:41時点における版
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(); } } } }
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