cs notebook1
  • Introduction
  • sort algorithm
  • Overloading VS Overriding
  • multithreading
  • Concurrency0
  • Concurrency1
  • ExecutorService
  • iteration & recursion
  • IO
  • Marker interface(Serializable, Clonnable&Remote)
  • Jackson Library
  • java.lang.System.*
  • Virtual Memory
  • Java ClassLoader
  • interfaceVSabstractClass
  • ENUM
Powered by GitBook
On this page
  • 0. Usage
  • 1 create a new thread
  • cat.start();
  • Thread t = new Thread(dog);
  • t.start();
  • 2. life cycle of a thread
  • 3.join(), wait(), notify(), notifyAll()
  • 3.1 notify() VS notifyAll()
  • 3.2 wait()
  • 3.3 join()
  • 4. Lock
  • 4.1 how to avoid deadlock?
  • 4.2 deadlock
  • 4.3 method
  • 5. Callable interface VS Runnable interface
  • 6.yield(),
  • 7.run() VS start()
  • 8. Daemon
  • 8.1 difference between Daemon threads and non-Daemon thread(user thread)

Was this helpful?

multithreading

0. Usage

trading system

1 create a new thread

  1. extends the thread class

  2. 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()

Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread t2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
   try {
      t1.join();
      t2.join();
      break;
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
}

Waits for this thread to die.

  1. The main thread creates and starts thet1 and t2 threads. The two threads start running in parallel.

  2. The main thread calls t1.join() to wait for the t1 thread to finish.

  3. The t1 thread completes and the t1.join() method returns in the main thread.

  4. The main thread calls t2.join() to wait for the t2 thread to finish.

  5. 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 thet1andt2threads 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,t1and/ort2could 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 thet1thread to finish. Thet2thread is running in parallel and is not affected byt1or thet1.join()call at all.

In terms of the try/catch, thejoin()throwsInterruptedExceptionmeaning 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

private final Lock lock = new ReentrantLock();

4.1 how to avoid deadlock?

  1. Don't use multithread.

  2. Always acquire the locks in the same order.

  3. 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.

PreviousOverloading VS OverridingNextConcurrency0

Last updated 6 years ago

Was this helpful?

To quote from the:

There is a thread that is running your example code which is probably the.

In , a deadlock is a state in which each member of a group is waiting for some other member to take action, such as sending a message or more commonly releasing a lock. Deadlock is a common problem in systems, , and , where software and hardware are used to handle shared resources and implement

So what is difference between start and run method? Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread. Most of the time calling run() is bug or because caller has intention of calling start() to create new thread and this error can be detect by many static code coverage tools like find bugs. If you want to perform time consuming task than always call start() method otherwise your will stuck while performing time consuming task if you call run() method directly. Another difference between start vs run in Java thread is that you can not call start() method twice on thread object. once started, second call of start() will throw IllegalStateException in Java while you can call run() method twice.

Thread.join()method javadocs
main thread
concurrent computing
multiprocessing
parallel computing
distributed systems
locks
process synchronization
http://javarevisited.blogspot.com/2016/08/useful-difference-between-callable-and-Runnable-in-Java.html#ixzz4sPustVSr
Thread Pool
http://www.geeksforgeeks.org/java-concurrency-yield-sleep-and-join-methods/
programming mistake
main thread