What to do to print 100?

I wanted to print 100 as a result in the next program.

I get 0 as an answer.

class s extends Thread{ int j=0; public void run() { try{Thread.sleep(5000);} catch(Exception e){} j=100; } public static void main(String args[]) { s t1=new s(); t1.start(); System.out.println(t1.j); } } 
+6
java multithreading
source share
4 answers

You have joined t1 to main. So parent thread(main()) will wait for the child thread to complete.

+5
source share

You need to wait for Thread complete. I added you a join call that blocks and wait for Thread complete before looking at the j value:

 class s extends Thread{ int j=0; public void run() { try{ Thread.sleep(5000); } catch( Exception e ){} j = 100; } public static void main(String args[]) throws InterruptedException { s t1=new s(); t1.start(); t1.join() ; // Wait for t1 to finish System.out.println(t1.j); } } 
+13
source share

Join t1

 t1.join 

so the main thread will wait

+2
source share

Just attach stream t1 to the main

 t1.join 
+2
source share

All Articles