I checked with jconsole and found there is not dead lock,but program does not exit

56 views Asked by At
{static int x;
    public static void main(String[] args) {
        Thread t2 = new Thread(()->{
            while(true) {
                if(Thread.currentThread().isInterrupted()) {
                    System.out.println(x);
                    break;
                }
            }
        },"t2");
        t2.start();
        new Thread(()->{
            sleep(1);
            x = 10;
            t2.interrupt();
        },"t1").start();
        while(!t2.isInterrupted()) {
            Thread.yield();
        }
        System.out.println(x);
    }

I verify the happen-before rule,I expect main-Thread and t2-Thread print value of x and exit,but the program is blocked in main thread.I tried to use jconsole to check dead lock and found no dead lock

1

There are 1 answers

2
prasad On

i found a way to fix it but i am not sure why it's behaving like this, still i am checking. check below code and follow my inline comments

{
 static int x;
    public static void main(String[] args) {
        Thread t2 = new Thread(()->{
            while(true) {
                if(Thread.currentThread().isInterrupted()) {
                    System.out.println(x);
                    break;
                }
              System.out.println("t2 completed");// if you add sop here then it's working as expected
            }
        },"t2");
        t2.start();
        new Thread(()->{
            sleep(1);
            x = 10;
            t2.interrupt();
        },"t1").start();
        while(!t2.isInterrupted()) {
            Thread.yield();
        }
        System.out.println(x);
    }

i am thinking thread t2 is not returning form the while loop as i called out still checking reason behind this Thanks