Hi techie's,
I have built a code, as such
We have four
java files :
thread2.java
thread1.java
SyncThread.java
threadController.java
exceuting each file in seperate command prompt.
thread1 and thread2 are files and each has a run method.
from the run method am calling the SyncMethod - synchronized method in a while loop at file SyncThread, where it just prints the values of astatic member variable SyncVariable.
ThreadController is the class that modifies the SyncVariable(Static) at SyncThread Class to 1.
but still those
thread 1 and thread 2 are displaying the value to be 0
Why ?
i have give the code ?
Please execute each file in a seperate command prompt!
The threadContrroller class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class threadController extends Thread implements Runnable
{
String str = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
void ControlMethod()throws Exception
{
while(true)
{
System.out.println("\n\nPlease Enter a valid code : ");
str = br.readLine();
int val = Integer.parseInt(str);
if(val == 1)
{
System.out.println("Setting SyncVariable to : 1");
SyncThread.ValueModifier(1);
}
}
}
public static void main(String args[])throws Exception
{
threadController objthreadController = new threadController();
objthreadController.ControlMethod();
}
}
this is the sync thread class
class SyncThread
{
static int SyncVariable;
public static void ValueModifier(int i)
{
SyncVariable = i;
}
public static synchronized void SyncMethod()
{
try
{
System.out.print("\n\n\t Threads Execute -> "+SyncVariable);
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("\n\n Exception e"+e);
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
class thread1 extends Thread
{
public void run()
{
SyncThread objSyncThread = new SyncThread();
try
{
while(true)
{
objSyncThread.SyncMethod();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
void Starter()
{
thread1 objThread1 = new thread1();
objThread1.start();
}
public static void main(String args[])throws Exception
{
thread1 objThread1 = new thread1();
objThread1.Starter();
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileWriter;
class thread2 extends Thread
{
public void run()
{
SyncThread objSyncThread = new SyncThread();
try
{
while(true)
{
objSyncThread.SyncMethod();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
void Starter()throws Exception
{
thread2 objThread2 = new thread2();
objThread2.start();
}
public static void main(String args[])throws Exception
{
thread2 objThread2 = new thread2();
objThread2.Starter();
}
}
Now execute this in seperate command prompts.
Why it did not show 1 when i modify the value