My expected output is
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5
I have tried synchronized and Lock but neither of them works. I reach to
Ending Main
sooner than I finish the loop completely. Current output is:
Starting Main
Count : 1
Count : 2
Count : 3
Count : 4
Ending Main
Count : 5
Any Idea why Count : 5 is after Ending Main? Here is my code:
public class Demo {
public static void main( String [] args ) {
System.out.println( "Starting Main" ) ;
for ( int i = 1 ; i <= 5 ; i++ ) {
Thread numberThread = new Thread(new NumberTask(i)) ;
numberThread.start() ;
}
System.out.println( "Ending Main" ) ;
}
}
class NumberTask implements Runnable {
private Lock bankLock = new ReentrantLock();
int count ;
public NumberTask( int count ) {
this.count = count ;
}
synchronized public void run() {
bankLock.lock();
try {
System.out.println( "Count : " + count ) ;
} finally {
bankLock.unlock();
}
}
}
You can use join() to wait for other thread to finish. Your code need to be updated as follows: