Java Parallel Program Basics

Source: Internet
Author: User

Java Parallel Program Foundation One, about the thread you have to know. Process and thread
    1. In a computer structure that waits for threading design, a process is a container for threads. As we all know, the program is a description of the instruction, the data and its organization, and the process is the entity of the program.
    2. Threads are lightweight processes and are the smallest unit of program execution. (PS: Use multithreading to design concurrent programs because the scheduling and switching costs between threads are much smaller than the process)
    3. The state of the thread (the Status class for thread):

      • new– the thread that you just created, you need to call the start () method to execute the thread;
      • runnable– thread is in execution state;
      • The blocked– thread encounters the synchronized synchronization block and pauses execution until the requested lock is received;
      • waiting– unlimited time to wait;
      • timed_waiting– have the time limit waiting;
      • terminated– execution finished, indicating the end.
Second, the basic operation of the thread create thread

code example: the Start () method creates a new thread and calls the run () Method!

new Thread();t.start();

Note The following code: This code can also be compiled for execution, but cannot create a new thread, but instead calls the run () method in the current thread. (PS: It is called as a normal method)

new Thread();t.run();

You cannot use Run () to open a thread, it only executes the run () method serially in the current thread.

In addition, the thread class has a very important construction method:
public Thread(Runnable target)
When this constructor is called at Start (), the new thread executes the Runnable.run () method. In fact, the default Thread.run () is also done this way .

public  class  mythread  implements  runnable  { public  static  void  main  (string[] args)        {Thread T = new  Thread (new  MyThread ());    T.start (); }  @Override  public  void  run  () {System.out.println ("; }}
    • After you define a thread in a way that inherits threads, you cannot inherit other classes, resulting in a greatly reduced scalability of the program. and the * * Overloaded **run () method is just like the normal method and is not invoked by the JVM actively.
    • Using the implement Runnable interface and passing the instance to thread, you can avoid overloading thread.run () and simply use the interface to define the thread.
Terminating a thread

Java provides a stop () method to close a thread, but this is a method that is labeled obsolete. The reason is that the stop () method is too violent and forcing execution to half of the thread shutdown may cause some data inconsistencies.

In a bunch of cases, don't use the Stop () Method!

Workaround: Define a tag variable stopme that indicates whether the thread needs to exit.

Thread break

In Java, there is an important thread-collaboration mechanism ———— thread interruption in order to improve thread-safe exit. ( note : Thread interrupts send a notification to the thread, but what happens when the thread is notified, it is the target thread's discretion)

    • Three important ways to interrupt a thread
    publicvoid Thread.interrupt()                  //中断线程    publicboolean Thread.isInterrupted()           //判断线程是否被中断    publicstaticboolean Thread.interrupted()      //判断线程是否被中断,并清除当前中断状态
    • Thread.interrupt()Method interrupts, the thread does not stop immediately, such as a dead loop body. The method can be used isInterrupted() to determine whether to jump out of the loop body.
Thread hibernation
  1. Thread.Sleep ()
    Leave the current thread dormant for several times, with the following signature:
    public static native void sleep(long millis) throws InterruptedException

    • Interruptedexception is not a run-time exception, and when the thread is dormant, it is thrown if it is interrupted.
    • The Sleep () method clears the interrupt token when the interrupt throws an exception. Therefore, you need to set the interrupt flag again in exception handling!
  2. Thread.wait () and notify ()
    These two methods are matched, one thread call obj.wait() is in the waiting state and another thread call is required obj.notify() to wake up. The obj object is an effective means of communication between multiple threads .

    • Object.wait () must be contained in the S ' y ' nchronzied statement , either wait () or notify () need to obtain a monitor of the target object first. (PS: Both methods release the monitor immediately after execution to prevent other waiting object threads from sleeping and all not performing properly)
    • Object.wait () also throws an InterruptedException exception.
    • The Object.notifyall () method wakes all waiting threads in the waiting queue.
  3. Suspengd () and resume ()
    The former is the thread hangs, the latter is the continuation of the execution, which is a pair of mutually compatible methods. These two are also obsolete methods , to understand the line.

    • Suspend () causes all resources of the dormant thread to not be freed until the resume () method is executed. (If two methods, which are executed before the former, the thread will have a difficult opportunity to be executed)
    • For a suspended thread, its state is Runnable , which can seriously affect our judgment on the current state of the system. (unforgivable)
  4. Join () and yield ()

    • Join () method
      Its signature is as follows:
      public final void join() throws InterruptedException;
      public final void join(long millis) throws InterruptedException;
      The first method represents an infinite wait, and the second method represents a certain amount of time to wait. The join () method blocks the current thread until the target thread ends, or the blocking time is reached.
      At the same time, the essence of the Join () method is to let the thread's Wait () method be raised on the current thread object instance.

    • Yield () method
      Its signature is as follows:
      public static native void yield();
      This static method causes the current thread to yield the CPU. (PS: But still will take the CPU resource Rob)

      When a thread is not that important or has a lower priority, you can call Thread.yield () at the appropriate time, giving other important threads more job opportunities.

About the complement of threading operations
    1. The difference between sleep () and wait ()
      Both object.wait () and Thread.Sleep () can allow threads to wait for several hours. In addition to the * * WAIT () can be awakened , another major difference: the **wait () method releases the lock on the target object, and the sleep () method does not release any resources .
Three, classified management: Thread Group

Simple set up a thread group ( code from the "Real Java High concurrency program Design" book )

 Public  class MyThread implements Runnable {     Public Static void Main(string[] args) {//Create a thread group called "Printgroup"Threadgroup TG =NewThreadgroup ("Printgroup"); Thread T1 =NewThread (TG,NewMyThread (),"T1");//Join thread GroupThread t2 =NewThread (TG,NewMyThread (),"T2");        T1.start (); T2.start ();//Because the thread is dynamic, Activecount () Gets an estimate of the total number of active threadsSystem.out.println ("Total Active threads ="+ Tg.activecount ());//Print thread information for outgoing groupTg.list ();//Note This method encounters a problem with the Thread.stop () methodTg.stop (); }@Override     Public void Run() {String groupandname = Thread.CurrentThread (). Getthreadgroup (). GetName () +"---"+ Thread.CurrentThread (). GetName (); while(true) {System.out.println ("I am"+ Groupandname);Try{Thread.Sleep ( the); }Catch(Interruptedexception e)            {E.printstacktrace (); }        }    }}
Iv. Daemon threads stationed in the background

Guardian Thread, is the guardian of the system, in the background to complete the systematic services, such as garbage collection thread, JIT thread and so on. when only a daemon thread is in a Java application, the Java virtual machine exits naturally .
To set a thread as a daemon thread:

        new Thread(new MyThread());        t.setDaemon(true);        t.start();

Note: The setup daemon must be set before the thread start () , otherwise it will get one IllegalThreadStateException , but the program and thread can still execute normally, but the thread is treated as a user thread only.

Five, Thread priority

Java threads can have their own priority. Due to the close relationship between the priority scheduling of the thread and the underlying operating system, the performance of the platform is different and cannot be controlled accurately.
In Java, use 1 to 10 to indicate thread priority. You can typically use three built-in static scalar representations:

    publicfinalstaticint1;    publicfinalstaticint5;    publicfinalstaticint10;

PS: The larger the number, the higher the priority (in general).

Six, synchronized keyword

Synchronized keyword usage simple record:

    • Specifies the lock object: Locks the given object and obtains the lock for the given object before entering the synchronization code.
    • Directly acting on the instance object: the equivalent of locking the current instance and getting the lock of the current instance before entering the synchronization code.
    • Directly acting on a static method: the equivalent of locking the current class, before entering the synchronization code to obtain the current class lock.

Synchronized can guarantee the atomicity, visibility, and ordering of threads (multiple threads that are restricted by synchronized are serially executed).

Vii. partial concealment of false records
    • The two threads that execute the (synchronized) synchronization code point to different runnable instances, that is, two threads use two different locks. Workaround : Modify the synchronization code to a static method.
    • Use a thread-insecure container, such as ArrayList, HashMap, and so on. workaround : Use a thread-safe container, such as Vector, Concurrenthashmap.
    • Invariant objects are locked, resulting in problems with critical section code control.
      • Immutable objects: Once an object is created, it cannot be modified.
        (for example, Integer i; i++ the essence is to create a new integer object and assign the reference to I, which involves the attribute of the integer reference)
Viii. references
    • "Practical Java High Concurrency Program Design" (Ge Yi Guo Chao)

Java Parallel Program Basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.