A Java program demonstrates the busy threading issue

Supposedly, this program should give a value of 20000 for the counter, but it will give different counter values each time you run it. This happens because 2 threads are allowed to access the same variable at the same time. For example, assume the counter is at 99

    1. Thread 1 takes the counter variable
    2. Thread 2 also takes the counter variable
    3. Thread 1 adds 1 to the counter, and the counter become 100.
    4. Thread 2 also addes 1 to the counter but it didn’t know the counter was updated by thread 1 already, the counter is still known as 99 for thread 2, so thread 2 adds 1 to the counter and save it as 100 when in fact it should be 101.

[code language=”java”]
public class BusyThread implements Runnable{

public static int counter=0;
private String name;

public BusyThread(String name)
{
this.name=name;
}

public void run()
{
int i=10000;
while(i>0)
{
BusyThread.counter++;
i–; //System.out.println(Thread.currentThread().getName()+" is adding 1");
}
System.out.println(this.name+": "+BusyThread.counter);
}

public static void main(String args[]) throws InterruptedException
{
Thread t1 = new Thread(new BusyThread("Thread 1"));
Thread t2 = new Thread(new BusyThread("Thread 2"));

t1.start();
t2.start();
System.out.println("This is printed after thread 1 and thread 2 are started.");
//Thread.sleep(5000);
while(t2.isAlive() || t1.isAlive())
{

}

System.out.println("Counter is: " + BusyThread.counter);

}

}
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search