I have a few questions on multithreading and waiting in Java on the following code.
/*
* Taken from
* https://www.wiley.com/en-us/Java+Programming%3A+24+Hour+Trainer%2C+2nd+Edition-p-9781118951453
*/
public class TestThreads3LambdaWait {
public static void main(String args[]) {
// Lambda expression for Market News
Runnable mn = () -> {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep (1000); // sleep for 1 second
System.out.println( "The market is improving " + i);
}
} catch(InterruptedException e ) {
System.out.println(Thread.currentThread().getName()
+ e.toString());
}
};
Thread marketNews = new Thread(mn, "Market News");
marketNews.start();
// Lambda expression for Portfolio
Runnable port = () -> {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep (700); // Sleep for 700 milliseconds
System.out.println( "You have " + (500 + i) +
" shares of IBM");
}
} catch(InterruptedException e ) {
System.out.println(Thread.currentThread().getName()
+ e.toString());
}
};
Thread portfolio = new Thread(port,"Portfolio data");
portfolio.start();
TestThreads3LambdaWait thisInstance = new TestThreads3LambdaWait();
synchronized (thisInstance) {
try {
thisInstance.wait(15000);
System.out.println("finished wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println( "The main method of TestThreads3Lambda is finished");
}
}
mn
and port
call notify()
when they finish executing? main()
is static, the code in main()
is not tied to a specific object.) thisInstance
, which is not tied to main()
since main()
is static). Is it because all TestThreads3LambdaWait
objects are notified because mn
and port
are in a static method and thus tied to every instance?notify(All)
anywhere inside it.Thread.sleep(15000)
would also do it, which is effectively what your wait
call does, given that nobody notifies.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.