Threads Flashcards
What does thread mean in Java?
Means two different things:
- An instance of class java.lang.Thread
- A thread of execution
How threads work in terms of memory?
Each thread has a separate call stack. main( ) has the main thread.
How does different JVM’s work for giving turns to threads?
Different JVM’s work in different ways. One might use round-robin fashion the other might not give turn to others until one finishes.
How does a thread begin in Java?
It begins as an instance of java.lang.Thread
Explain run( ) method
The job that needs to be done in the separate thread goes into run. It is either in java.lang.Thread or in the implementation of Runnable interface.
How does extending Thread class works?
You have to override run method i.e. public void run()
You can overload it but it will be ignored and even if you call it yourself it won’t have a separate call stack. But it is not a good design choice. And on a separate note - Thread itself extends Runnable.
How does implementing Runnable works?
You implement Runnable and override run i.e. public void run()
How do we instantiate a thread that extends Thread?
It is simple. Just; MyThread t = new MyThread();
How do we instantiate a thread that implements Runnable?
This time we need worker and job classes. Thread is the worker that runs the thread-specific code and Runnable is the job class that runs the job that needs to be done.
First instantiate;
MyRunnable r = new MyRunnable();
Next get instance of Thread and give your runnable;
Thread t = new Thread(r);
The Runnable you pass to the Thread constructor is called the target or the target Runnable.
What happens when no args are passed to Thread()?
Thread calls its own run( ) method.
What happens when same target is passed to multiple Threads?
You can pass a single Runnable instance to multiple Thread objects so that the same Runnable becomes the target of multiple threads.Giving the same target to multiple threads means that several threads of execution will be running the very same job (and that the same job will be done multiple times)
What are some thread constructors?
- Thread()
- Thread(Runnable target)
- Thread(Runnable target, String name)
- Thread(String name)
How do we start a thread?
t.start();
before start is called the thread is said to be in new state. We start a Thread not a Runnable.
What happens when start is called?
- A new thread of execution starts (with a new call stack).
- The thread moves from the new state to the runnable state.
- When the thread gets a chance to execute, its target run() method will run.
Does this code start a new call stack?
Thread t = new Thread();
t.run();
No. Calling run in Runnable does not start a new call stack.
How can we print name of a Thread?
We can call getName() method of the thread that executes the that Runnable’s run() method. But we do not have a reference to current thread, so that’s how it is done:
Thread.currentThread().getName()
Does a thread still has a name even if we do not name it?
Yes. For main thread its “main” and for other threads its like “Thread-0”
What happens when a thread completes its run() method?
The stack for that thread dissolves and the thread is considered dead. It’s still a thread object and methods on that object can be invoked as any other Java object. But it’s not a thread of execution any more. And we can not call start() on that object again.
What happens when we try to start a Thread second time?
It can not be started and IllegalThreadStateException is thrown.
What does getId() method returns when invoked on a thread?
It returns the id of thread. It’s positive, unique, long and a thread’s only id for the thread’s entire life.
What is thread scheduler?
It’s part of JVM and decides which thread is going to actually run from all of the eligible ones i.e. in runnable state. And also decides which will be out of the run state.
In which order threads are chosen by thread scheduler?
The order in which runnable threads are chosen to run is not guaranteed.
What are thread states?
- New
- Runnable
- Running
- Waiting/blocked/sleeping
- Dead
Define “New” thread state
The state after Thread is instantiated. It’s a thread object but not a thread of execution yet. start() method has not been invoked yet. It is not alive.
Define “Runnable” thread state
The thread is eligible to run but not selected by scheduler yet. It can be after start() is called or returned back from a blocked, waiting or sleeping state. It’s considered alive.
Define “Running” thread state
When a runnable is selected by scheduler from thread pool. That’s the only way to be in running state.
Define “Waiting/blocked/sleeping” thread state
The thread is alive but not eligible to run in this state. It can blocked waiting for a resource or it might be sleeping by the code.
Define “Dead” thread state
When a thread completes the thread’s state is dead and can not be brought back to life. If start() is invoked on this thread. runtime exception is thrown.
Define “Sleeping” state details
sleep() is a static method and can be called from code
Thread.sleep(). sleep can throw checked InterruptedException
How does timer is Thread.sleep() works?
It makes the current thread sleep “at least” for the specified time. It returns back to runnable after time finishes but it might not be returned back to running by scheduler. It’s a static method and one thread can not put another one into sleeping.
Do threads have any priorities?
Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases, the range is less than 10). The scheduler in most JVMs uses preemptive, priority-based scheduling (which implies some sort of time slicing). This does not mean that all JVMs use time slicing. In most cases, the running thread will be of equal or greater priority than the highest-priority threads in the pool. But never rely on thread priorities since it is not guaranteed.
How is thread priority set?
By default a thread gets the priority of the thread that creates it. Or it can be set by calling setPriority() on the thread object. JVM will never change a priority. And 1-10 is not guaranteed since some JVM’s have range 1-5.In that case different priorities might be mapped to same one.
How does yield() work?
When a thread calls yield, it goes from running to runnable to give turn to other same priority threads. But the behaviour is not guaranteed!
How does join() work?
A thread is joined to end of another thread. If you join B to A, B is executed when run() of A completes and A becomes dead.
What does the code below mean?
Thread t = new Thread();
t.start();
t.join();
“Join me (the current thread) to the end of t, so that t must finish before I (the current thread) can run again.”
You can also call one of the overloaded versions of join() that takes a timeout duration so that you’re saying, “wait until thread t is done, but if it takes longer than 5,000 milliseconds, then stop waiting and become runnable anyway.”
Define other ways where a thread can leave running state?
- The thread’s run() method completes.
- A call to wait() on an object (we don’t call wait() on a thread).
- A thread can’t acquire the lock on the object whose method code it’s attempting to run.
- The thread scheduler can decide to move the current thread from running to runnable in order to give another thread a chance to run. No reason is needed—the thread scheduler can trade threads in and out whenever it likes.
What is a race condition?
Multiple threads can access the same resource (typically an object’s instance variables) and can produce corrupted data if one thread “races in” too quickly before an operation that should be “atomic” has completed.
How to protect data from race conditions?
- Mark the variables private
* Synchronize the code that modifies the variables