Can I synchronize access to the count and count2 without using the synchronized method?

 public class Lasttask{ int count1; int count2; public static void main(String[] args) { final Lasttask lt = new Lasttask(); new Thread(){ public void run(){ for(int i=0;i<1000;i++){ lt.count1++; try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } lt.count2++; System.out.println(lt.count1); System.out.println(lt.count2); System.out.println(""); } } }.start(); new Thread(){ public void run(){ for(int i=0;i<1000;i++){ lt.count1++; try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } lt.count2++; System.out.println(lt.count1); System.out.println(lt.count2); System.out.println(""); } } }.start(); } } 

1 answer 1

You can use a synchronized block of code:

 synchronized(monitor) { lt.count++; } 

Or use AtmoicInteger:

 AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); 
  • If I'm not mistaken, the volatile modifier will help here. - Yevgeny Karpov
  • 2
    @Yevgeny Karpov are wrong, i.e. lt.count ++ non-atomic operation. - a_gura