2.3 KiB
Theoretical Questions
1. start() vs run()
-
What output do you get from the program? Why?
Calling run() Running in: main Calling start() Running in: Thread-2→ When
t1.run()is called directly, we're calling therun()method like a normal method and no new thread is created. Therun()method is executed on the current thread (main); soThread.currentThread().getName()returns "main".
Whent2.start()is called:start()creates a new thread named "Thread-2". The new thread automatically callsrun()soThread.currentThread().getName()returns "Thread-2". -
What’s the difference in behavior between calling
start()andrun()? →start(): creates a new thread and is executed on a new thread.run(): method doesn't create new thread and is executed on the current thread.
2. Daemon Threads
-
What output do you get from the program? Why?
Main thread ends. Daemon thread running...→ The thread is set as a Daemon thread. The main thread ends immediately after printing "Main thread ends." and the JVM exits without waiting for the daemon thread to complete its loop.
-
What happens if you remove
thread.setDaemon(true)?→ The thread becomes a user thread. The main thread still ends, but the JVM will not exit because there is still a live user thread. The program will print all 20 "Daemon thread running..." messages.
-
What are some real-life use cases of daemon threads?
→ Spell Checker / Grammar Checker in Word.
3. A shorter way to create threads
-
What output do you get from the program?
Thread is running using a ...! -
What is the
() -> { ... }syntax called?→ lambda expression
-
How is this code different from creating a class that extends
Threador implementsRunnable?→ The code uses a lambda expression to define the
run()method inline. When you extendThread, you must create a separate subclass, override therun()method, and then instantiate that subclass. This gives you the ability to add new fields or methods to your thread class, but it also means you cannot extend any other class. When you implementRunnableusing an anonymous class (the old way before lambdas), you write:new Runnable() { public void run() { ... } }.