Hi,
I am trying to use a static vairable in my thread class to start and stop the thread by setting the variable true/false, but this does not seems to work.
I am attaching the code below:
//Thread Class
class MyThread extends Thread
{
volatile static boolean status = false;
long duration;
MyThread()
{
this.duration = 1000;
}
MyThread(long duration)
{
this.duration = duration;
}
public void run()
{
while (status)
{
System.out.println("MyThread::run::Going to sleep !!");
try
{
sleep(duration);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("MyThread::run::Woke Up !!");
}
}
public static void setStatus(boolean flag)
{
status = flag;
}
}
//I use this class to start the thread
class StartThread
{
public static void main(String s[])
{
MyThread th = new MyThread(1000);
MyThread.setStatus(true);
th.start();
System.out.println("MyThread::status::After Thread start:: "+MyThread.status);
}
}
//Use this class to stop the thread
class StopThread
{
public static void main(String s[])
{
MyThread.setStatus(false);
}
}
I might have missed out a very basic stuff somewhere in my code. From my understanding this should work, but it is not
So plz. let me know where am I wrong.
Thanks & Regards
Ankur
I am trying to use a static vairable in my thread class to start and stop the thread by setting the variable true/false, but this does not seems to work.
I am attaching the code below:
//Thread Class
class MyThread extends Thread
{
volatile static boolean status = false;
long duration;
MyThread()
{
this.duration = 1000;
}
MyThread(long duration)
{
this.duration = duration;
}
public void run()
{
while (status)
{
System.out.println("MyThread::run::Going to sleep !!");
try
{
sleep(duration);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("MyThread::run::Woke Up !!");
}
}
public static void setStatus(boolean flag)
{
status = flag;
}
}
//I use this class to start the thread
class StartThread
{
public static void main(String s[])
{
MyThread th = new MyThread(1000);
MyThread.setStatus(true);
th.start();
System.out.println("MyThread::status::After Thread start:: "+MyThread.status);
}
}
//Use this class to stop the thread
class StopThread
{
public static void main(String s[])
{
MyThread.setStatus(false);
}
}
I might have missed out a very basic stuff somewhere in my code. From my understanding this should work, but it is not
So plz. let me know where am I wrong.
Thanks & Regards
Ankur