-1

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?

JavaHopper
  • 5,567
  • 1
  • 19
  • 27
Magnus2005
  • 97
  • 3
  • 13
  • 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 Answers1

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