2016-08-11 3 views
-1

스레드가 실행되는 동안 카운터의 값을 가져 오는 방법이있는 새 스레드에서 카운터를 만들고 싶습니다. 어떻게하면 쉽게 할 수 있습니까?Java Inter Thread Communication

+0

http://www.tutorialspoint.com/java/java_thread_communication.htm는이 옵션을 선택합니다. 여기 예제 : http://stackoverflow.com/questions/2170520/inter-thread-communication-in-java – sixtytrees

+0

그냥 카운터 인 경우 'AtomicInteger'유형을 사용할 수 있습니다. – Leon

답변

2

확인이 :

public class ThreadsExample implements Runnable { 
    static AtomicInteger counter = new AtomicInteger(1); // a global counter 

    public ThreadsExample() { 
    } 

    static void incrementCounter() { 
      System.out.println(Thread.currentThread().getName() + ": " + counter.getAndIncrement()); 
    } 

    @Override 
    public void run() { 
      while(counter.get() < 1000){ 
       incrementCounter(); 
      } 
    } 

    public static void main(String[] args) { 
      ThreadsExample te = new ThreadsExample(); 
      Thread thread1 = new Thread(te); 
      Thread thread2 = new Thread(te); 

      thread1.start(); 
      thread2.start();   
    } 
}