Forum Stats

  • 3,839,340 Users
  • 2,262,485 Discussions
  • 7,900,937 Comments

Discussions

creating an unsafe thread program

924690
924690 Member Posts: 1
edited Mar 18, 2012 11:29PM in Java Desktop Applications
good 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();

}

}

Answers

This discussion has been closed.