Javaでコルーチンもどき
Javaでも真面目にスケジューラ書けば,スレッドを1つ1つ割り当てられたオブジェクト群を順番どおり動かせる,という実験
スケジューラの動き
for (Ball b:balls) { try { synchronized (this) { b.resume(); wait(); } } catch (InterruptedException e) { e.printStackTrace(); } b.draw(g); }
オブジェクトの動きはこんな感じ
public void run() { while(true) { x+=vx; y+=vy; suspend(); } } public void suspend() { try { synchronized (scheduler) { scheduler.notify(); } synchronized(this) { wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } public void resume() { if (started) { synchronized(this ) { notify(); } } else { started=true; new Thread(this).start(); } }