Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * コルーチンもどき クラス
- * 派生してaction()をオーバーライドして使ってね。
- */
- import android.util.Log;
- public class Corouchan implements Runnable{
- Object lock_ = new Object();
- Object returnLock_ = new Object();
- Thread thread_;
- boolean exit_ = false;
- boolean exitDone_ = false;
- // スレッドスタート
- public void start() {
- thread_ = new Thread(this);
- thread_.start();
- synchronized (returnLock_) {
- try {
- // Thread.sleep(1000);
- returnLock_.wait();
- } catch (InterruptedException e) {
- Log.d("corouchan", "InterruptedException@start");
- e.printStackTrace();
- }
- }
- }
- // スレッド終了 (終了要求を出す。即座には停止しない)
- public void end() {
- exit_ = true;
- synchronized (lock_) {
- lock_.notifyAll();
- }
- }
- // 終了要求がきているか?
- public boolean isExit() {
- return exit_;
- }
- // 終了を完了したか?
- public boolean isExitDone() {
- return exitDone_;
- }
- @Override
- public void run() {
- action();
- exitDone_ = true;
- synchronized (returnLock_) {
- returnLock_.notifyAll();
- }
- }
- /**
- * ユーザーアクション
- * ここにコルーチンで実行したい処理を記述
- * yiedl() を呼ぶと呼び出し元に戻る
- */
- public void action() {
- Log.d("corouchan", "POS1");
- if ( yield() ) return;
- Log.d("corouchan", "POS2");
- if ( yield() ) return;
- Log.d("corouchan", "POS3");
- if ( yield() ) return;
- Log.d("corouchan", "POS4");
- if ( yield() ) return;
- Log.d("corouchan", "POS5");
- }
- // コルーチンの処理を一時停止して、呼び出し元に戻る
- private boolean yield() {
- synchronized (returnLock_) {
- returnLock_.notifyAll();
- }
- try {
- synchronized (lock_) {
- lock_.wait();
- }
- } catch (InterruptedException e) {
- Log.d("corouchan", "InterruptedException@yield");
- e.printStackTrace();
- }
- return exit_;
- }
- // コルーチンの次の処理を実行
- // 戻り値: ture:成功 false:失敗(すでにコルーチンは終了しているなど)
- public boolean next() {
- if ( exit_ || exitDone_ ) return false; // すでに終了している
- synchronized (lock_) {
- lock_.notifyAll();
- }
- try {
- synchronized (returnLock_) {
- returnLock_.wait();
- }
- return true;
- } catch (InterruptedException e) {
- Log.d("corouchan", "InterruptedException@next");
- e.printStackTrace();
- }
- return false;
- }
- }
- /* サンプル
- Corouchan c = new Corouchan();
- c.start(); // この時点で「pos1」が出力される
- for ( int i=0; i<10; i++ ) {
- c.next(); // next()を呼ぶとコルーチンに制御が戻る
- // i==3 の段階で「pos5」が出力され、以降はなにも起きない
- }
- c.end();
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement