One thread increases an integer named "counter" , and another decreases the same integer. Using synchronized statement on LockObject to control access to counter. If i understand correctly i have to use an Object reference. Can i use synchronized statement on counter somehow? public class Synchronized_Block_Demo { public static int counter=1; public static Object LockObject = new Object(); public static void Show_LockObject(){ System.out.println("LockObject = " + counter); } public static void main(String[] args) throws InterruptedException { Runnable r0=null,r1=null; Thread a,b; r0=new Thread_increases_LockObject(); r1=new Thread_decreases_LockObject(); a=new Thread(r0); b=new Thread(r1); a.start(); b.start(); a.join(); b.join(); System.out.print("Threads finished!"); } } class Thread_increases_LockObject implements Runnable{ …

Member Avatar
Member Avatar
+0 forum 7

public class Thread8 implements Runnable { Demo d; public static void main(String r[]) { new Thread8().disp(); } void disp() { d = new Demo(); new Thread(new Thread8()).start(); new Thread(new Thread8()).start(); } public void run() { d.fun(Thread.currentThread().getId()); } } class Demo { static long f=0; synchronized void fun(long id) { for(int i=1; i<3; i++){ System.out.println(id); Thread.yield(); } } } The program compiles properly but gives a NullPointerException. Why? Why did it not give a compile error for using a non-static reference variable d [Demo d] in static context i.e. in void disp()?

Member Avatar
Member Avatar
+0 forum 2

The End.