java multithreading and concurrency - the first chapter

A difference, process and thread

The process is the smallest unit of resource allocation, the thread is the smallest unit of CPU scheduling

  • All process-related resources, are recorded in the PCB
  • Scheduling process is to seize the processor unit; threads belonging to a process and to share its resources
  • Only by the thread stack register, program counter, and the composition of TCB

to sum up

  • Thread can not be seen as a standalone application, and the process can be seen as a standalone application
  • Processes have separate address space, not affect each other, just different execution paths threading process
  • Thread does not have a separate address space, programs and more robust than the process of multi-threaded programs. Because a thread hang the whole process will hang, but hang a process, other processes can proceed.
  • Switching process larger than thread switching overhead

Java relations processes and threads

  • Java function provided by the operating system package, including processes and threads
  • Run a program will produce a process, the process includes at least one thread
  • Each process corresponds to a JVM instance, multiple threads share the JVM heap
  • Single-threaded Java programming model, the program automatically creates the main thread
  • The main thread can create a sub-thread, in principle, to be completed after the child thread execution

Second, the difference between the start and run to the thread

  • Call start () method creates a new child thread and start
  • One common method of calling run () method of just Thread

Three, Thread and Runnable what relationship

  •  Thread is a class that implements the Runnable interface, so run support multithreading
  • Since java class is a single inheritance principle, it recommended more use Runnable Interface

How to run () method pass parameters

  • The constructor parameter passing
  • Member variable parameter passing
  • The callback function parameter passing

How to deal with the return value of the thread

  • The main thread wait method: while loop determines whether a return value, continue useless SLEEP;
  • Use join Thread class () blocks the current thread to wait for the child thread processed;
  • By FutureTask Or get the thread pool: Callable interface through

Obtaining FutureTask

public class MyCallable implements Callable<String>{

    @Override
    public String call() throws Exception{
        String value = "test";
        System.out.println("Ready to work");
        Thread.currentThread.sleep(5000);
        System.out.println("task done");
        return value;
   }
}

  

public class FutureTaskDemo{

    public staitc void main(String[] args){
        FutureTask<String> task = new FutureTask<String>(new MyCallable());
        new Thread(task).start();
        if(!task.isDone){
          System.out.println("task has not finished ,please wait");
          }
          System.out.println("task return: "+ task.get());
    }
}

Obtaining thread pool

public class ThreadPoolDemo{

     public static void main(String[] args){
          ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
          Future<String> future = newCachedThreadPool.submit(new MyCallable());
          if(!future.isDone()){
              System.out.println("task has not finished, please wait");
          }
          try{
             System.out.println(future.get());
          }catch(InterruptedException e){
             e.printStackTrace();
          }the catch (ExecutionException E) { 
             e.printStackTrace (); 
          } the finally {
             // when the last thread pool must remember the shutdown 
            newCachedThreadPool.shutdown (); 
          } 
     } 

}

Fourth, the state of the thread

Six states:

  • New (New): After creating a state not yet started threads
  • Run (Runnable): contains Running and Ready
  • Wait indefinitely (Waiting): not assigned CPU execution time, the display need to be awakened; for example: Object.wait Timeout parameter is not set () method; Thread.join Timeout parameter is not set () method; LockSupport.park Method .
  • Waiting period (Time Waiting): wake up automatically by the system after a certain time; for example: Thread.sleep () method; Timeout parameter setting of the Object.wait () method; the Thread.join Timeout parameter set () method; LockSupport. parkNanos () method; LockSupport.parkUntil () method.
  • Blocked (Blocked): waiting to acquire an exclusive lock
  • End (Terminated): status has been terminated thread, the thread has completed execution.

Fifth, the difference between sleep and wait

The basic difference

  • sleep is a Thread class method, wait method is defined in the class Object.
  • sleep () method can be used anywhere
  • wait () method can only be used in a method of synchronized or synchronized block

The main essential difference

  • Thread.sleep will only make the CPU, the lock will not lead to changes in behavior
  • Object.wait not only let the CPU, will release the synchronization lock resources already occupied

Difference six, notify and notifyall of

Two concepts

  • Lock pool EntryList: A hypothesis thread already has an object (not class) lock, and another thread B, C wants to call a synchronized method of this object (or block), due to the B, C thread into the object synchronized method (or block) must first obtain the prior ownership of the object lock, which happens to lock the object is currently being occupied by the thread a, while the B, C thread will be blocked into a place to wait for locks to be released this place is the object lock pool.
  • Wait pool WaitSet: A thread calls a wait suppose an object () method, thread A releases the lock of the object while thread A enters into a waiting pool of the object, into the thread pool will not wait to compete lock of the object.

The difference notify and notifyAll

  • NotifyAll opportunity to make all the threads in a wait pool all entered the lock pool to compete to acquire a lock
  • notify only randomly selected in a pool of threads waiting to enter the lock pool to compete for the opportunity to acquire a lock.

Seven, yield

The concept: When you call Thread.yield () function, the thread scheduler will give a current thread is willing to let a hint of CPU use, but the thread scheduler may ignore this hint.

the yield will not let the current thread lock.

Eight, interrupt function

The method has been abandoned

  • By calling the stop () method to stop a thread
  • By calling suspend () and resume () method

Current methods used

  • Call interrupt (), notify the thread should interrupted.
  1. If the thread is blocked state, the thread will immediately exit the blocked state, and throw an InterruptedException exception.
  2. If a thread is in a state of normal activity, then the thread will interrupt flag is set to true. Interrupt flag is set thread will continue to run normally, is not affected.
  • Thread needs to be called with interrupts
  1. In normal operation the task, always check the interrupt flag in this thread, if the interrupt flag is set to stop on their own thread
  2. If the thread is in the normal active state, then the thread will interrupt flag is set to true. Interrupt flag is set thread will continue to run normally, is not affected.

 

Guess you like

Origin www.cnblogs.com/dasha/p/11007556.html