Threads Flashcards
How does single core systems have multiple threads?
Time-Slicing.
What is a thread?
A lightweight process. A process is used for heavyweight tasks like executing an application. Threads exist in a process. Threads share process resources.
What is multi-threading?
Example: word prints docmnent but also accepts user input typing.
What are critical sections?
Code that modifies data structures shared by multiple threads.
What is synchronization?
When code of one thread is in critical section it’s important another thread isn’t allowed in critical section. Signaled and unsignalled.
In Java, how to start a thread?
Provide runnable object (implements Runnable). Must have run() method. Runnable object then passed to Thread constructor. Must also invoke Thread.start().
How do you make thread sleep?
Thread.sleep(msec);
What is an interrupt? How is interrupt done?
A thread should stop what it’s doing and do something else. Use try catch for interrupted exception and return out of catch block.
How do you get name of current thread?
Thread.currentThread().getName();
How do you check if a thread is alive?
t.isAlive() - it returns a Boolean
How to wait for thread t? How to interrupt thread t?
t. join(msec);
t. interrupt();
What is thread contention?
When two or threads try to access the same resource simultaneously and as a result they execute more slowly or not at all.
How to make a method synchronized?
public synchronized void increment(){}
Write a synchronized statement:
synchronized (this){}
What is deadlock?
Two or more threads blocked forever, waiting for each other.