Hey everyone~! I am pretty new to threading but I'm trying to figure it out by playing around with its possibilities. I wrote a program where 2 threads are supposed to "race" to count to 10 and then the first one there says "I win!" and the second says "I lose...". However, I am having issues as both say "I win!" How do I fix this??? I keep playing around with it but I can't get it to work.
public class BetaClass implements Runnable
{
private String name;
private int counter = 1;
private static volatile boolean alreadyWon = false;
private Thread executor;
public BetaClass(String name)
{
this.name = name;
executor = new Thread(this);
executor.setDaemon(true);
executor.start();
}
public void run()
{
while (counter<10)
{
System.out.println(name+": "+counter);
try
{
executor.sleep(500);
}
catch (InterruptedException ie) {}
finally{counter++;}
}
run2();
}
public synchronized void run2()
{
if (!alreadyWon)
{
System.out.println(name+": I win~!");
alreadyWon = true;
}
else
System.out.println(name+": I lose...");
}
public static void main(String[] args)
{
BetaClass alpha = new BetaClass("Alpha");
BetaClass beta = new BetaClass("Beta");
}
}