multithreading - Can I keep a counter for Java Threads in the run method? -
i have class variable, sum. every time start new thread, want sum increment. seems run being called once, , can't find better info tell me more it. there way accomplish locks? here simple code:
public class myclass implements runnable{ static int sum = 0; public static void main(string[] args) throws interruptedexception { for(int = 0; < 5; ++i){ thread t = new thread(new myclass()); t.start(); t = null; } } @override public synchronized void run() { ++sum; system.out.println(sum); } }
keeping mutable state in static variables bad practice, how fix work:
public class myclass implements runnable { static atomicinteger counter = new atomicinteger(0); public static void main(string[] args) throws interruptedexception { (int = 0; < 5; ++i) { thread t = new thread(new myclass()); t.start(); t = null; } } @override public void run() { int sum = counter.incrementandget(); system.out.println(sum); } }
Comments
Post a Comment