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(); } }