multithreading
0. Usage
trading system
1 create a new thread
extends the thread class
implement the Runnable interface.
eg:
public Cat extends Thread{
public Cat(){
}
//override the run meathod
public void run(){
......
}
}
public Dog implements Runnable{
public Dog(){}
}
public void run(){
.....
}
}
Cat cat= new Cat();
cat.start();
//begin the new thread of dog
Dog dog = New Dog();
Thread t = new Thread(dog);
t.start();
2. life cycle of a thread
new, runnable, running, non-runnable(wait(), blocked()), terminated.
3.join(), wait(), notify(), notifyAll()
package newThreadTest;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class MultiThread7 {
public static void main(String[] args){
final Processor7 processor = new Processor7();
Thread t1= new Thread(new Runnable(){
public void run(){
try {
processor.produce();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2= new Thread(new Runnable(){
public void run(){
try {
processor.consume();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
try {
t1.join(xx);//main thread continue the work until the child thread finish( or working for xx miliseconds)
t2.join();// child thread call the join meathod.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Everything is done.");
}
}
class Processor7{
public void produce() throws InterruptedException{
synchronized (this){
System.out.println("Producer thread running ......");
wait();//release the key, change into wait state.
System.out.println("Resumed.");
}
}
public void consume() throws InterruptedException{
Scanner scanner = new Scanner(System.in);
Thread.sleep(2000);
synchronized(this){
System.out.println("Waiting for return key.");
scanner.nextLine();
System.out.println("Return key pressed.");
notify();//wake up the thread which is in wait state and need the same key.
System.out.println("Notification is sent.");
Thread.sleep(5000);
}
}
}
3.1 notify() VS notifyAll()
notify(): wake one thread which is required the same lock
notifyAll(): wake all the threads which are required the same lock.
3.2 wait()
the thread run to wait method, then release the lock it holds and change into wait statue.
3.3 join()
Waits for this thread to die.
The main thread creates and starts thet1 and t2 threads. The two threads start running in parallel.
The main thread calls t1.join() to wait for the t1 thread to finish.
The t1 thread completes and the t1.join() method returns in the main thread.
The main thread calls t2.join() to wait for the t2 thread to finish.
The t2 thread completes (or completed before the t1 thread did) and thet2.join()method returns in the main thread.
It is important to understand that thet1
andt2
threads have been running in parallelbut the main thread that started them needs to wait for them to finish before it can continue. That's a common pattern. Also,t1
and/ort2
could have finished_before_the main thread callsjoin()
on them. If so thenjoin()
will not wait but will return immediately.
t1.join()
means cause t2 to stop until t1 terminates?
No. The_main_thread that is callingt1.join()
will stop running and wait for thet1
thread to finish. Thet2
thread is running in parallel and is not affected byt1
or thet1.join()
call at all.
In terms of the try/catch, thejoin()
throwsInterruptedException
meaning that the main thread that is callingjoin()
may itself be interrupted by another thread.
4. Lock
class lock: only use on static function
object lock: always use object lock
4.1 how to avoid deadlock?
Don't use multithread.
Always acquire the locks in the same order.
Release the resources after a period of time.
4.2 deadlock
4.3 method
lock();
unlock();
5. Callable interface VS Runnable interface
1) callable can return result
2) callable can throw checked exception
Callable can return result and throw checked exception but you need ExecutorService to execute Callable instance. Good thing is that both Runnable and Callable are SAM type so you can use them in lambda expressions.
Read more:
6.yield(),
basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.
Theoretically, to ‘yield’ means to let go, to give up, to surrender. A yielding thread tells the virtual machine that it’s willing to let other threads be scheduled in its place. This indicates that it’s not doing something too critical. Note that it’s only a hint, though, and not guaranteed to have any effect at all.
Let’s list down important points from above definition:
Yield is a Static method and Native too.
Yield tells the currently executing thread to give a chance to the threads that have equal priority in the
There is no guarantee that Yield will make the currently executing thread to runnable state immediately.
It can only make a thread from Running State to Runnable State, not in wait or blocked state.
Note:
Once a thread has executed yield method and there are many threads with same priority is waiting for processor, then we can't specify which thread will get execution chance first.
The thread which executes the yield method will enter in the Runnable state from Running state.
Once a thread pauses its execution, we can't specify when it will get chance again it depends on thread scheduler.
Underlying platform must provide support for preemptive scheduling if we are using yield method.
7.run() VS start()
8. Daemon
Daemon thread is a low priority thread (in context of JVM) that runs in background to perform tasks such as garbage collection (gc) etc., they do not prevent the JVM from exiting (even if the daemon thread itself is running) when all the user threads (non-daemon threads) finish their execution. JVM terminates itself when all user threads (non-daemon threads) finish their execution, JVM does not care whether Daemon thread is running or not, if JVM finds running daemon thread (upon completion of user threads), it terminates the thread and after that shutdown itself.
8.1 difference between Daemon threads and non-Daemon thread(user thread)
The main difference between Daemon thread and user threads is that the JVM does not wait for DAemon thread before exiting while it waits for user threads, it does not exit until unless all the user threads finish their execution.
Last updated
Was this helpful?