Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

creating an unsafe thread program

924690Mar 18 2012 — edited Mar 18 2012
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();

}

}

Comments

Processing
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Apr 15 2012
Added on Mar 18 2012
3 comments
1,936 views