Bookmark and Share

Front Back
How do java threads relate to stacks and heaps?
Threads share a heap but keep their own stacks.
What's the biggest difference between user and daemon threads
An app must wait until all user threads are complete before exiting whereas it can exit if there are still daemon threads are executing.
What classes does thread functionality come from?
java.lang.Thread java.lang.Object
What is needed to create a new thread?
A Thread object. And this object needs to call a run() method ---> It can call it's own or if it's constructor was called with a Runnable object it will use the run() of that Runnable object.
In the world of Threads what method holds the ""job"" the Thread is supposed to perform?
Why must you never call the run() method directly?
You CAN call the run() method directly BUT realize all manual calls to run() DO NOT create a new thread of execution. You must call a thread's start() method to generate a new/separate stack of execution -- the thread will then automatically call run().
Thread t = new Thread(new Thread()); t.start(); Explain why this fails to compile.
It doesn't fail to compile. Thread implements Runnable interface so it can be used as a Runnable object passed to another Thread. In this example the run method of the passed in thread would be called. Notice also that the Thread passed as an argument wouldn't start a new thread of execution itself. It acts as a standard object whose run() method would be called.
Can you pass the same job to many different threads? How?
Runnable r = new Runnable() { public void run(){ for(int i=0; i<10; i++) System.out.println(""I'm the job in "" + Thread.currentThread().getName()); } }; Thread t1 = new Thread(r); t1.setName(""t1""); Thread t2 = new Thread(r); t2.setName(""t2""); Thread t3 = new Thread(r); t1.start(); t2.start(); t3.start(); *** HERE IS OUTPUT ON MY MACHINE **** I'm the job in t1 I'm the job in t1 I'm the job in t1 I'm the job in t1 I'm the job in t1 I'm the job in t1 I'm the job in t1 I'm the job in t1 I'm the job in t2 I'm the job in Thread-2 I'm the job in t2 I'm the job in Thread-2 I'm the job in t2 I'm the job in Thread-2 I'm the job in t2 I'm the job in Thread-2 I'm the job in t2 I'm the job in Thread-2 I'm the job in t2 I'm the job in Thread-2 I'm the job in t1 I'm the job in t2 I'm the job in t1 I'm the job in t2 I'm the job in t2 I'm the job in t2 I'm the job in Thread-2 I'm the job in Thread-2 I'm the job in Thread-2 I'm the job in Thread-2 Press any key to continue...
What is the definition of the Runnable interface?
interface Runnable { void run(); } NOTE: that interface methods are always public and abstract. To implement the call to run() must appear like this: public void run() { ... stuff here ... }
When does a thread become ""alive"" ""dead""? Can a thread exist before it's alive after it's dead?
A thread is alive the moment it's start() method is called. start() causes: -new thread/stack of execution -thread moves from new state to runnable state A thread becomes dead when it's run() method finishes. Once dead you cannot restart. This means you CANNOT CALL START() ON A DEAD THREAD. But a thread DOES exist before it's alive and after it's dead!!! A thread certainly might be instantiated before it's start() method called. AND A THREAD OBJECT STILL EXISTS EVEN IF IT'S FINISHED RUNNING AND IT'S SEPARATE STACK GONE AWAY. So you can call methods on this ""dead"" object. Only it's separate call stack is dead. It's objectness is still very much in tact.
How do you get the name of a thread?
What is the default naming scheme of a thread?
Thread - N Where ""N"" is the thread count number. Main thread is N=0.
When is a thread in the ""new"" state?
After it's been instantiated and before start() has been called.
What happens when you call start() method on a dead thread?
IllegalThreadStateException is thrown at runtime. Code with attempted restarting of dead threads does compile.
What is the major difference between Thread class methods sleep()/yield() and join()/setPriority() ???
sleep() & yield() are static and only work on the currently operating thread. join()/setPriority() are called on thread instances.
How would you make a thread sleep for 2 seconds?
Since you cannot make other threads sleep you'd have to put the sleep call inside the run() method that is being used by the thread you want to put to sleep. Argument to sleep() takes milliseconds (and optionally a second argument of nanoseconds). Milli means thoudandths. So 1 second = 1 000 milliseconds. Thread.sleep(2000); You'd have to make this sleep call in a try block because the checked exception InterruptedException can be thrown by sleep()
What 3 thread related methods does java.lang.Object provide?
all public final void wait() throws InterruptedException notify() notifyAll()
Why have Thread methods suspend() and resume() been depricated?
Because they allow 1 thread to directly control another thread - a bad idea. stop() is also depricated.
What's the only promise made by sleep() method regarding time?
It promises that the currently executing thread will sleep for at least the time declared in the sleep() method call (or if it returns sooner than that it will thrown an InterruptedException).
What does Thread.yield() guarantee?
It guarantees that the currently operating thread will allow the scheduler to decide if it wants to let another thread a chance to run. A scheduler may be implemented so that is ignores yield calls (rare but possible) and lets the currently operating thread go until it's finished. So.... a yield() call might cause the current thread to move to Runnable state (vs. the Running state). Or it may have no affect at all. NO GUARANTEES ON WHAT THE SCHEDULER WILL DO.
When a thread is created what is it's priority?
It adopts the priority of it's creator.
Are thread priorities numbered 0-10 or 1-10.
Machine dependent. No guarantees on how many priority categories there will be or what values they'll be. Use setPriority(integer) to adjust a Thread instance's priority. You can use static final variables defined in Thread class to avoid having to know the machine dependent names of priorities. Thread.MAX_PRIORITY Thread.NORM_PRIORITY Thread.MIN_PRIORITY
Give a quick summary of what is happening the following code: Thread t2 = new MyThread(); t2.start(); t2.join();
Thread t2 = new MyThread(); t2.start(); t2.join(); There are 2 threads in this example: 1) The currently executing thread (#1) 2) The thread with the reference t2 (#2) This join says #1 should wait until #2 is dead (no longer running) before it continues. join() can throw InterruptedException (just like sleep can) so it must be called in a try clause. Also can call with a millisecond time (mt) which says ""Wait for other thread to finish but if it takes longer than mt then stop blocking and become runnable again.
What is ""race condition""?
It's a multi-threading problem when thread operations are not atomic. One thread will perform 1 part of an operation another thread ""races in"" and makes a change to the state of the data and then the original thread tries to complete it's initial operation. This problem does not occur if the operation is made atomic or the original thread can keep all others out until it completes it's operation.
What does synchronizing guarantee?
It doesn't promise that a thread will get to keep running but it does promise that once a thread synchronizes ON A PIECE OF DATA that no other thread will be able to act on that same data even if the thread is moved out of the running state.
int i; How do you synchronize access to this integer?
You can't apply the ""synchronized"" modifier to variables or classes only to methods (and blocks). So encapsulate your data in getters and setter methods that you then synchronize. private int i; synchronized int getI(){return i;} synchronized void setI(int i){this.i = i;}
When a method is synchronized what gets locked?
The object that contains the method. If an object is locked not only can other threads not run that method that caused the locking but other threads are not allowed to run any method in that object which are marked synchronized. Static synchronized methods get locks on Classes not instantiated objects but work very similarly. You can hold a lock on a static Class and an object instance of type Class at the same time.
If a thread is inside a synchronized method (and thus it's acquired a lock) and that method encounters a Thread.sleep() call does the object release the lock while it's sleeping?
No. Think about it. It's still in the synchronized code and should keep holding the lock.
What if a thread obtains a lock on an object and then tries to enter a second synchronized method in the same object. Since the lock is already owned (by itself) will it every be able to obtain the second lock which just so happens to be the same lock it holds?
There is no acquiring of a second lock nor does the thread need to acquire it again. If a thread owns a lock it can get into all of that object's synchronized methods w/out having to reacquire or acquire extra locks.
How might 2 threads get deadlocked?
Thread A and B both need to obtain locks 1 and 2 to perform a task. Thread A gets #1 Thread B gets #2 Thread A will hold #1 until it can get #2 and Thread B will hold #2 until it can get #1. They will wait infinitely for the other lock to become available. This is deadlock. If both A & B obtained locks in same order dead lock wouldn't occur.
How do you synchronize on a block? Why would you use this?
void aMeth(){ data protection needed... synchronized(this){ ... protected stuff... } } In this example the lock is held for a shorter period of time. The short the better. You might also want to synch on a third party object. (use the object instead of ""this"") or you might want to lock on a class: synchronized(MyClass.class) { } NOTE: Class locks end w/ the .class extension. These are called class literals. Every class has an instance of a Class object that represents it. Another way to get this Class object: Class cl = Class.forName(""MyClass""); You can sync on this ref to the Class object. synchronized(cl) {}
Why do static and non-static synchronized methods block each other?
They don't. They actually get locks on different objects (the Class object vs. the instance object).
Do different instances of the same type of object (i.e. 2 different Dog objects) use the same lock?
No. 2 different objects so 2 different locks.
What's the golden rule of mixing static and non-static synchronized code?
Don't. When attempting to make your object thread safe restric synching on static data to synchronized methods and synching on instance vars to synchronized non-static instance methods. Because static and non-static synchrnoized methods lock on DIFFERENT LOCKS if you allow both to access the same piece of data neither will keep the other out (as they are locking on different objects).
Core java offers some thread safe objects. Are these objects always thread-safe?
No. Each method might be synchronized but what if you then perform a broader behavior that involves calling a few of these thread-safe methods? The broader behavior is not atomic which means it's not thread safe.
What MUST a thread have before calling wait() notify() or notifyAll()?
A lock on the object on which these methods are called. Thus all calls to these 3 methods must take place inside synchronized methods or blocks. NOTE: NOTICE that these 3 methods are called on objects! When you call wait() inside a synchronized method you're actually calling this.wait() on the current object.
How do you call wait() if you're synchronizing on a block that uses a 3rd party object?
synchronized (thirdPartyObj){ thisPartyObj.wait(); } NOTE: If you just call wait() then you'll be waiting to be notified about the current object and NOT the thirdPartyObj object.
What might wait() throw that notify() and notifyAll() don't throw?
InterruptedException Make sure then to call wait() in a try clause.
x of y cards