Advanced multi-threaded Java syntax 10-

Multithreading

Concurrency and parallel process, thread scheduling its own Baidu

Thread (thread): is a process in which the basic unit of scheduling an execution path, CPU scheduling of. The same process threads can share some memory (heap, the method area), each thread has its own independent space (stack, program counter). Because of shared memory between threads, in terms of data sharing, more convenient, but also because of the sharing of data, there will be thread-safety issues.

When running a Java program, in fact, already it has a thread, and that is the main thread.

Thread class

All thread object must be an instance of the Thread class or subclass, the Java Thread class through inheritance in to create and multi-threaded startup steps are as follows:

  1. Subclass definition of the Thread class, the class and override run () method, the method body of the run () method represents the thread needs to complete the task, so the run () method is called thread of execution.

  2. Create a Thread subclass instance, the thread object is created

  3. Call the thread object's start () method to start the thread

Runnable Interface

We can also implement Runnable, override run () method, and then start the agents and the implementation of our body threads run () method of the Thread class through an object. Proceed as follows:

  1. Runnable interface implementation class is defined, the interface and override run () method, the method body run () method of the same thread of execution threads.

  2. Create an instance of Runnable implementation class and use it to create an instance of the Thread Thread object as a target, the Thread object is the real thread object.

  3. Call the thread object's start () method to start a thread.

Example: public class MyRunnable implements Runnable // define the implementation class thread

    MyRunnable mr = new MyRunnable (); // create thread objects

         Thread t = new Thread (mr) ; // Thread class by way of example, the thread start
          t.start ();

Virtually all multi-threaded code is by start () method of the Thread run to run. Therefore, whether to inherit the Thread class or implement Runnable interface to achieve multi-threaded, ultimately controlled by API thread Thread object, familiar with the Thread class API is the foundation for multi-threaded programming.

tips: Runnable objects only as target Thread object, Runnable class comprises implement the run () method as the only thread of execution. The actual thread object is still the Thread instance, just this Thread thread is responsible for the implementation of the method of its target's run ().

The difference between the two approaches

1, a single inheritance restriction inheritance, the way to achieve more than can be achieved

2, different start-up mode

3. Inheritance: when implementing a shared data may need to be static

  Implementation: As long as a Runnable implementation class share the same object can be.

4. Inheritance: When you select this lock may not be used,

  Implementation: When you select this lock can be used.

Anonymous inner class object to create and start to implement threads

( "! new thread") {the Thread new new
  @Override
  public void RUN () {
    for (int I = 0; I <10; I ++) {
      System.out.println (getName () + ": being executed!" + I);
    }
  }
} .start ();

Construction method

public Thread (): Allocates a new Thread object.

public Thread (String name): assign a new thread object a specified name.

public Thread (Runnable target): Allocates a new Thread object with the specified target.

public Thread (Runnable target, String name): assign a new thread object with the specified objectives and specify the name.

Thread common method

volatile : Modified variables

At what point are not necessarily variable value will be changed, in order to always get the latest value, after volatile modified so every time to value from main memory, it will not be cached value in a register.

Daemon thread

Daemon thread has a feature that if all non-daemon threads have died, then the daemon thread is automatically killed.

Call setDaemon (true) method can set the specified thread as a daemon thread. It must be set before the thread is started, otherwise it will be reported IllegalThreadStateException exception.

Call isDaemon () can determine whether the thread is a daemon thread.

Thread Safety

Judge thread safety issues

1, if there are multiple threads

2, whether to use multiple threads that share data

3, these threads when using shared data, whether there is a read write

Sync block

synchronized keyword can be used in the process of a block, it indicates that only enforcing mutually exclusive access to resources of this block. format:

synchronized (sync lock) {
     need code synchronization operations
}

Synchronization lock must be an object

Lock objects can be of any type.

Multiple threads objects must use the same lock . Note: At any time, at most one thread can own synchronization lock, who got into the lock on the block, other threads can only wait outside (BLOCKED).

Synchronization method

Use synchronized modified method, called synchronization methods to ensure that the thread holding the lock when performing the method, other threads can only be to the methods waiting

] [Other modifiers synchronized return type method name (parameter list []) throws Exception List] [{
     // the code may produce thread safety issues
}

Lock object can not be selected by our own, it is the default:

(1) Static method: the lock object is the object of the current class Class

(2) non-static way: this

Inter-thread communication

When the "data buffer" full, "producer" need to wait, waiting to be awakened;

When the "data buffer" empty, "consumers" need to wait, waiting to be awakened.

When a thread meet certain conditions, to enter the wait state ( wait () / wait (Time) ), and then wait for it to wake up (after completion of the specified code to perform their other threads the Notify () ); or you can specify the wait time of , so time to automatically wake up; when there are multiple threads to wait, if necessary, use notifyAll () to wake up all waiting threads.

  1. wait: the thread is no longer active, no longer involved in scheduling, into the wait set, so do not waste CPU resources, not to compete lock, then thread state that is WAITING or TIMED_WAITING. It have to wait for the other thread to perform a particular action , that is, " notice (the Notify) " or wait for time to, in this objects waiting thread is released from the wait set and re-enter to the dispatch queue (ready queue )in

  2. notify: a notification target thread wait set is selected in the release;

  3. notifyAll: All threads on the notification object wait set is released.

note:

After being awakened may not be able to resume execution thread immediately notify, because it had interrupted the place is in sync blocks, but at the moment it no longer holds the lock, so she needs to try again to acquire the lock (likely to face other threads competition), after the success can resume execution in place after the original call wait method.

Summarized as follows:

  • If you can get a lock, the thread becomes RUNNABLE (run) status from WAITING state;

  • Otherwise, the thread from WAITING state and becomes BLOCKED (wait for locks) state

Call wait and notify methods need to pay attention to the details

  1. wait and notify methods method must be called by the same lock object. Because: the corresponding lock object can be woken notify the use of threads after the wait method call with a lock object.

  2. notify and wait method is a method belonging to the class of Object. Because: lock object can be any object, any object which belongs to the class are inherited Object class.

  3. notify and wait method must be used in the method of synchronization code block or a synchronizing function. Because: must call this method through two lock object.

Wait wake-up mechanism to solve the classic "producer-consumer" problem

To solve this problem, we must let the producer thread waits in the buffer is full (wait), pause into the blocked state, wait until the next consumer consumes data in the buffer when the notification (notify) is waiting thread resumes to the ready state, start adding data to the buffer. vice versa

Thread Life Cycle

First, the angle of the thread on standing: five kinds

1, New: create a thread object, yet start

2, ready: already started, and can be CPU scheduling

3, run: being scheduled

4, blocking: met: sleep (), wait (), wait (time), the other thread join (), join (time), suspend (), the lock is occupied by other threads, etc.

  Back to unblock ready state: sleep () time, notify (), wait time to, the end of the thread stopper, stopper to time, resume (), the other thread holding the lock release the lock.

5, death: run () ends normally encountered an unhandled exception or error, stop ()

note:

New state program can only thread calls start (), and can only be called once, if the thread of the new non-state, as has been started threads or thread has died calling start () will error IllegalThreadStateException exception.

Second, the stand angle of the six kinds of code

Such enumeration defined in the class java.lang.Thread.State

public enum State {
  NEW,
  RUNNABLE,
  BLOCKED,
  WAITING,
  TIMED_WAITING,
  TERMINATED;
}

1, New NEW: create a thread object, yet start

2, run RUNNABLE: CPU can be scheduled, or is scheduled

3, blocked BLOCKED: wait for the lock

4, wait WAITING: wait (), join () and so there is no set time, etc. must notify (), or stoppered end of the thread to resume

5, there is time to wait TIMED_WAITING: sleep (time), wait (time), join (time) and so have time blocking, so time to recover, or interrupt will be restored

6, termination TERMINATED: run () ends normally encountered an unhandled exception or error, stop ()

Operation and release the lock deadlocks

Any thread into the synchronized block, before the synchronization method, you must first obtain a lock on the synchronization of the monitor, so when it will release the lock on the synchronization monitor it?

1, the release operation of the lock

The current thread synchronization method, the synchronization code block execution ends .

The current thread appeared untreated Error or Exception block synchronization code, the synchronization process, resulting in an abnormal end of the current thread.

The current thread executes the code block synchronization lock object, the synchronization method wait () method, the current thread is suspended, and release the lock.

2, will not release the lock operation

线程执行同步代码块或同步方法时,程序调用Thread.sleep()、Thread.yield()方法暂停当前线程的执行。

线程执行同步代码块时,其他线程调用了该线程的suspend()方法将该线程挂起,该线程不会释放锁(同步监视器)。应尽量避免使用suspend()和resume()这样的过时来控制线程。

3、死锁

不同的线程分别锁住对方需要的同步监视器对象不释放,都在等待对方先放弃时就形成了线程的死锁。一旦出现死锁,整个程序既不会发生异常,也不会给出任何提示,只是所有线程处于阻塞状态,无法继续。

 

Guess you like

Origin www.cnblogs.com/Open-ing/p/11953108.html