读书人

游戏中点染线程与更新线程交替执行

发布时间: 2012-06-27 14:20:08 作者: rapoo

游戏中渲染线程与更新线程交替执行

private final State mThreadLocker = new State();
?private UpdateThread updateThread;
?private DrawThread drawThread;

?@Override
?public void onCreate(Bundle savedInstanceState) {
??super.onCreate(savedInstanceState);
??setContentView(R.layout.main);
??updateThread = new UpdateThread();
??updateThread.start();
??drawThread = new DrawThread();
??drawThread.start();
?}

?protected void onUpdate() throws InterruptedException {
??final State threadLocker = this.mThreadLocker;
??threadLocker.waitUntilCanUpdate();
??System.out.println("Update");
??threadLocker.notifyCanDraw();

?}

?public void onDrawFrame() throws InterruptedException {
??final State threadLocker = this.mThreadLocker;
??threadLocker.waitUntilCanDraw();
??System.out.println("Draw");
??threadLocker.notifyCanUpdate();

?}

?private class UpdateThread extends Thread {
??private boolean flag; // 线程执行标志位

??public UpdateThread() {
???super("UpdateThread");
???this.flag = true;
??}

??@Override
??public void run() {
???try {
????while (flag) {
?????onUpdate();
????}
???} catch (final InterruptedException e) {
????this.interrupt();
????e.printStackTrace();
???}
??}

??/*
?? * 停止线程
?? */
??public void requestStop() {
???flag = false;
??}
?}

?private class DrawThread extends Thread {
??private boolean flag; // 线程执行标志位

??public DrawThread() {
???super("DrawThread");
???this.flag = true;
??}

??@Override
??public void run() {
???try {
????while (flag) {
?????onDrawFrame();
????}
???} catch (final InterruptedException e) {
????this.interrupt();
????e.printStackTrace();
???}
??}

??/*
?? * 停止线程
?? */
??public void requestStop() {
???flag = false;

??}
?}

?private static class State {
??boolean mDrawing = false;

??public synchronized void notifyCanDraw() {
???this.mDrawing = true;
???this.notifyAll();
??}

??public synchronized void notifyCanUpdate() {
???this.mDrawing = false;
???this.notifyAll();
??}

??public synchronized void waitUntilCanDraw() throws InterruptedException {
???while (this.mDrawing == false) {
????this.wait();
???}
??}

??public synchronized void waitUntilCanUpdate()
????throws InterruptedException {
???while (this.mDrawing == true) {
????this.wait();
???}
??}
?}

?@Override
?protected void onStart() {
??super.onStart();
?}

?@Override
?protected void onResume() {
??super.onResume();
?}

?@Override
?protected void onPause() {
??super.onPause();
?}

?@Override
?protected void onStop() {
??super.onStop();
?}

?@Override
?protected void onDestroy() {
??super.onDestroy();
??updateThread.requestStop();
??drawThread.requestStop();
?}

?@Override
?public String toString() {
??return "MultiThreadAndSync";
?}

读书人网 >移动开发

热点推荐