Android- Thread.join() causes Application to hang
android, multithreading
Solution
When you call `myThread.join()` inside `Activity.onCreate` you block the main UI thread. Of course it looks like your application has stopped responding because the UI thread is the one responsible for redrawing UI. All your calls `runOnUiThread` never happen because your UI thread is busy waiting on your game loop.
Problem
I have a thread which handles my game loop, when i call .join() on this thread the application stops responding. I've been trying to fix a problem where the programs never get to the code, I.E the thread never ends. ``` System.out.println("YAY"); ``` My Thread for the Game Loop: This thread successfully prints out "Game Ended" but never seems to finish. ``` Runnable startGameLoop = new Runnable() {//game loop @Override public void run() { AiFactory ai = new AiFactory(); final Button play = (Button) findViewById(R.id.Play); final Button pass = (Button) findViewById(R.id.Pass); while(finish==false){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } currentPlayer = game.getPlayer(); if(currentPlayer.isPlayer()==false){ //System.out.println("passCount:" +game.getPasscount()); ai.decide(nextPlay, game.getPreviousPlayed(), currentPlayer, game.getPasscount() ); if(nextPlay.size()!=0){ runOnUiThread(new Runnable(){ public void run(){ changeArrow(); if(nextPlay.size() ==1){ play1Card(); } else if(nextPlay.size()==2){ play2Card(); } else if(nextPlay.size()==3){ play3Card(); } else if(nextPlay.size()==5){ play5Card(); } } } else{ game.addPassCount(); game.nextTurn(); runOnUiThread(new Runnable(){ public void run(){ changeArrow(); } }); } } else if (currentPlayer.isPlayer()==true){ runOnUiThread(new Runnable(){ public void run(){ changeArrow(); play.setClickable(true); if(game.getPasscount()==3){ pass.setClickable(false); } else{ pass.setClickable(true); } } }); } } System.out.println("Game Ended"); } }; ``` Starting and joining the thread to the main thread: ``` Thread myThread = new Thread(startGameLoop); myThread.start(); try { myThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("YAY"); } ``` To my understanding .join() makes the current thread wait till the new thread has finished before carrying on. Sorry if this is a stupid question, i'm quite new to threading.