creating an unsafe thread program
924690Mar 18 2012 — edited Mar 18 2012good day all, please I've been battling with this program. what I will like to do is to find a way of increasing the value of the counter in the while loop (inside the run() method) until it comes to a point where “Unsafe operation detected” is printed to screen. Please could any one help me with this? here is my code:
class Counter implements Runnable
{
private int counter;
boolean flag = false;
public int get()
{
return counter;
}
public void set(int n)
{
counter = n;
}
public void increment()
{
int temp1 = counter;
counter++;
int temp2 = counter;
if( temp1 == temp2 || (temp2-temp1) > 1 )
setFlag();
}
public boolean getFlag()
{
return flag;
}
public void setFlag()
{
flag = true;
}
public void run()
{
set(0);
while( get() < 10 )
{
//counter++;
increment();
}
if (getFlag() == true )
System.out.println( "Unsafe operation detected" );
else
System.out.println( "Fortuitously executed successfully");
}
public static void main(String[] args)
{
Runnable myRun = new Counter();
Thread t1 = new Thread(myRun);
Thread t2 = new Thread(myRun);
t1.start();
t2.start();
}
}