2015-01-26 3 views
1

이 코드는 내가 그것을 여러 번 터치하면 빨리 내가이 outprint를 얻을 버튼스레드가 Android에서 다른 스레드를 시작할 때까지 기다리는 방법은 무엇입니까?</p> <p>I/System.out에 : 1</p> <p>I/시스템

//Thread called when click a button 
    Thread a = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      synchronized ((Object) contadordeMierda){ 
       Random rn = new Random(); 
       int n= rn.nextInt(10) + 1; 
       contador++; 

       try { 
        Thread.sleep(n*100); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 

       System.out.println(contador); 
      } 
    } 
    }); 

    a.start(); 

를 클릭 할 때마다 호출된다. 아웃 : 2

I/System.out에 5

I/System.out에 5

I/System.out에 : 9

I/System.out에 : 9

I/System.out에 : 9

I/System.out에 : 9

I/시스템. 아웃 : 9

...

어떻게 내가 다른 일을 시작 끝까지 하나 개의 스레드 대기 위해 무엇을 할 수 있는가? 그래서 인쇄가갑니다 1 2 3 4 5 6 7 8 9 10 11 12 ...?

+1

나는 안드로이드에 대해 완전히 잘 모르겠지만, 내가 있다고 생각하기가 어려운 찾을 것 버튼 클릭은 비동기 적으로 처리되기 때문에 스레드가 올바른 순서로 시작되지 않는다는 것이 아니라 실행 순서가 보장되지 않습니다. 단일의 backing thread 또는 유사하게 ExecutorService를 사용하는 편이 낫다. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html –

+1

자물쇠'contadordeMierda'는 어디에서 어떻게 선언합니까? – iForests

+0

내부 run() {synchronized ((Object) contadordeMierda) {... Object에 캐스트하지 않으면 에러가 발생합니다 –

답변

1

정확한 목적은 join() function입니다. 여러 번 묻는 질문 : How to wait for a number of threads to complete?.

+0

어떻게 사용할 수 있습니까? int가 올바른 값을 가질 것을 어떻게 보장 할 수 있습니까? 두 링크의 –

+0

에는이를 사용하는 방법이 설명되어 있습니다. 스레드 내부에서'int'를 초기화하면 명령을 보장 할 수 없습니다. int를 쓰레드의 범위 밖에 두거나 처음에 쓰레드에 넘겨 줘라. – logoff

-1
왜 이런 식으로하지

: 현재 실행중인 스레드가 존재하지 않는 경우 새 스레드 만 시작하자 :

private boolean isThreadRunning = false;//declare a boolean field to store thread status whether it's running or not 
... 

if(!isThreadRunning){ 
    Thread a = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      synchronized ((Object) contadordeMierda){ 
       Random rn = new Random(); 
       int n= rn.nextInt(10) + 1; 
       contador++; 

       try { 
        Thread.sleep(n*100); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 

       System.out.println(contador); 
       isThreadRunning = false;//Set the boolean variable to false because the thread has completed it's operations. 
      } 
    } 
    }); 

    a.start(); 
    isThreadRunning = true;// Set the boolean to true because thread.start has been called. 

} 
+0

내가 스레드를 처음부터 순서대로 시작하기를 원하기 때문에 그럴 수 없다. –