繁体   English   中英

从单线程到多线程android studio

[英]From single thread to multi thread android studio

我正在制作太空入侵者游戏。 这是主要活动:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Get a Display object to access screen details
    Display display = getWindowManager().getDefaultDisplay();
    // Load the resolution into a Point object
    Point size = new Point();
    display.getSize(size);
    spaceInvadersEngine = new SpaceInvadersEngine(this, size.x, size.y);
    setContentView(spaceInvadersEngine);

}

    // This method executes when the player starts the game
    @Override
    protected void onResume() {
        super.onResume();

        // Tell the gameView resume method to execute
        spaceInvadersEngine.resume();
    }

    // This method executes when the player quits the game
    @Override
    protected void onPause() {
        super.onPause();

        // Tell the gameView pause method to execute
        spaceInvadersEngine.pause();
    }

SpaceInvadersEngine有两个主要函数update()完成所有计算和draw()绘制所有元素。 添加更多元素后,游戏可以运行但速度很慢,因此我决定将其拆分为更多线程。 这是我在SpaceInvadersEngine代码

  public void resume() {
    playing = true;
    gameThread = new Thread(runnable);
    gameThread.start();

    drawThread = new Thread(this);
    drawThread.start();
}

gameThread runnable 我有

while(playing){update();}

对于run() drawThread ,我只有draw();

当游戏加载并准备新关卡(创建新的入侵者和升级对象)时,它最多需要 5 秒并冻结游戏。 如何消除等待时间? 当我drawThreadrunnable尝试drawThread时,它不会绘制任何东西。

另外,由于某种原因,当我使用两个线程时,我的ship有时会在一帧中随机闪烁为一个大图像,然后恢复正常,它不是在单线程中闪烁吗?

我建议你使用 Kotlin 语言和协程来处理异步代码。 开始使用并不难,它确实可以提高整体性能和代码可读性。

fun exampleMethod() {
    // Starts a new coroutine on Dispatchers.Main as it's the scope's default
    val job1 = scope.launch {
        // New coroutine with CoroutineName = "coroutine" (default)
    }

    // Starts a new coroutine on Dispatchers.Default
    val job2 = scope.launch(Dispatchers.Default + "BackgroundCoroutine") {
        // New coroutine with CoroutineName = "BackgroundCoroutine" (overridden)
    }
}

如果你愿意稍微改变技术,看看这个并尝试协程。 这是如何在 Android 上处理长时间运行的任务的一种新颖而出色的方式。 此外,您可以找到许多文章和示例。 使用 Kotlin 协程提高应用程序性能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM