I have a shared boolean static variable uninitialized and created two threads, started one thread, then sleep of two seconds and then started second thread.
I have print statements basically in both the threads based on the shared variable condition but I am getting different output when ran in c# and java
C# code:
class ThreadCache
{
public static bool shared;
public static void Main()
{
new Thread(Meth1).Start();
Thread.Sleep(2000);
new Thread(Meth2).Start();
}
public static void Meth1()
{
while (!shared) { }
Console.WriteLine("Hello");
}
public static void Meth2()
{
shared = true;
Console.WriteLine("Hi");
}
}
Java Code:
public class HiHello
{
static boolean S1 = false;
public static void main(String[] args) throws InterruptedException {
new Thread(new Thread1(), "Thread 1").start();
Thread.sleep(2000);
new Thread(new Thread2(), "Thread 2").start();
}
private static class Thread1 implements Runnable
{
public void run()
{
while (!HiHello.S1) {}
System.out.println("HELLO!");
}
}
private static class Thread2 implements Runnable
{
public void run()
{
HiHello.S1 = true;
System.out.println("HI!");
}
}
}
In C# whatever number of times I run the code I get both outputs "Hi" and "Hello" but when I run in java only "Hi" gets printed and the programs never terminates(exits). Please explain me the reason of getting different outputs