I want to create a counter in a new Thread that has a method to get the value of the counter while the thread is running. How can I do it in an easy way?
            Asked
            
        
        
            Active
            
        
            Viewed 206 times
        
    -1
            
            
        - 
                    http://www.tutorialspoint.com/java/java_thread_communication.htm Check this. Example itself from here: http://stackoverflow.com/questions/2170520/inter-thread-communication-in-java – sixtytrees Aug 11 '16 at 12:56
- 
                    If it is just a counter you can use an `AtomicInteger` type. – Leon Aug 11 '16 at 12:57
1 Answers
2
            
            
        Check this:
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();          
     }
}
 
    
    
        beeb
        
- 1,615
- 1
- 12
- 24
 
    