Multithreaded Programming Learning One (Java Multi-Threading Foundation)

Source: Internet
Author: User

I. Concepts of processes and threads

process: The execution of a program is called a process, each process has separate code and data space, the cost of inter-process switching is relatively large, a process contains 1-n threads. a process is the smallest unit of resource sharing .

Threads: the same class of threads share code and data space, each thread has a separate run stack and program counter (PC), the thread switching overhead is small, and the thread is the smallest unit of CPU scheduling.

Multi-process: refers to the operating system can run multiple tasks (Programs).

Multithreading: refers to the same program has multiple sequential flows in the execution, the thread is the process of internal single control sequence flow.

second, the advantages of multithreading

The single-threaded feature is queued execution, which is synchronization. and multithreading can maximize the use of CPU idle time to deal with other tasks, the system's operating efficiency greatly improved, using multithreading is also performed asynchronously.

third, the use of multi-threading

There are two main ways to realize multithreaded programming, one is to inherit the thread class and the other is to implement the Runable interface. In fact, when you create a new thread by inheriting the thread class, the biggest limitation is that it does not support multiple inheritance, because the Java language is characterized by a single inheritance, so in order to support multiple inheritance, it is possible to implement the Runnable interface and inherit on one side. But the threads created in both ways are the same in nature at work, with no essential difference.

 public  class  Thread1 "extends   private  int  count=5; @Override  public  void   run () { for  (int  i=0;i<2;i ++) {System.out.println ( is now thread +currentthread (). GetName () + "in execution:" +count--); }    }}
 Public class Implements Runnable {    privateint count=5;    @Override    publicvoid  run () {        for (int i=0;i <2;i++) {            System.out.println ("Now is Thread" +thread.currentthread (). GetName () + "in execution:" +count--);}    } 
 Public classtest{ Public Static voidMain (string[] args) {//integrating the Thread classThread1 thread1=NewThread1 (); Thread T1=NewThread (Thread1, "A"); Thread T2=NewThread (Thread1, "B"); Thread T3=NewThread (Thread1, "C");        T1.start ();        T2.start ();        T3.start (); //implementing the Runable interfaceThread2 thread2=NewThread2 (); Thread T4=NewThread (Thread2, "A2"); Thread T5=NewThread (Thread2, "B2"); Thread T6=NewThread (Thread2, "C2");        T4.start ();        T5.start ();    T6.start (); }}

The results are shown to illustrate the following two points:

1, the CPU on the thread scheduling is uncertain, the use of "preemptive-type" scheduling.

2, for the internet is often said that the implementation of the Runnable interface thread can realize the sharing of data, and inherited thread is not. In fact, the difference between the two is only a single inheritance limit and some usage differences (for example, if you want to do something about this thread object (such as GetName), then you have to call the Thread.CurrentThread () method to get a reference to this thread), There is no real difference.

Why is the start () method instead of the run () method called when multithreaded execution? If the calling code Thread.run () is not executed asynchronously, but is synchronous, then the thread object will not be handed over to the thread planner for processing. Instead, the run () method is called by the main main thread, which means that you must wait until the code in the Run () method finishes to execute the following code. Start () is used to start a thread, when the start () method is called, the system will open a thread, through the Thead class in the Start () method to launch a thread in a ready state (operational state), at this time is not running, once the CPU time slice, will automatically start to execute run () Method.Four, synchronized key words

Multi-threaded locking mechanism, through the multi-threaded to call the method before the Synchronized keyword, so that multiple threads in the execution method, the first attempt to take the lock, if you can get the lock, then this thread can execute synchronize inside the code. If you can't get the lock, the thread will keep trying to get the lock until it gets the lock. Synchronized can be locked on any object and method, and the lock code is called a "mutex" or "critical section".

The Synchronized keyword is used primarily to ensure that the current thread is not preempted by other threads during execution, and that shared resources are modified, causing thread insecurity to occur.

v. Common threading Methods

1. Thread.CurrentThread () Method: Returns the information that the code snippet is being invoked by which thread. The most common is thread.currentthread (). GetName ().

2,isAlive () method: Determines whether the current thread is active. What is active state? The active state is that the thread has started and has not been terminated. Threads are considered "alive" when the thread is running or ready to start running.

3. Thread.Sleep () method: Allow the executing thread to hibernate (suspend execution) within the specified number of milliseconds. This "executing thread" refers to the thread returned by This.currentthread ().

4,getId () method: Gets the unique identity of the thread.

5,Thread.Interrupt () method: used in the thread break, here need to note In fact, the role of Thread.Interrupt is not in the disconnection process, but "the notification thread should be interrupted", specifically whether the interruption or continue to run, should be handled by the notified thread itself. Specifically, when you call Interrupt () on a thread,

① If a thread is in a blocked state (such as in a sleep, wait, join, and so on), the thread exits the blocked state immediately, throws a Interruptedexception exception, and clears the stop state value so that it becomes false.
② if the thread is in a normal active state, the interrupt flag for that thread is set to true, that's all. The thread that is set on the interrupt flag will continue to function normally, unaffected.

New Thread ((), {    while ( !  Thread.interrupted ()) {//through this to check whether this interrupt flag bit is set to true, whether to make program logic, please do not use obsolete thread.stop, Thread.Suspend, Thread.Resume         // do more work .     }}); Thread.Start (); // after some time thread.interrupt ();

It is worth mentioning that there are two ways to determine whether a thread is interrupted:

    • Interrupted (): Tests if the front thread is already in the interrupt state, after execution has the function of false to clear the status flag. (It is important to note that even if mythread.interrupted (), the test is still the state of the current thread).
    • Isinterrupted (): Tests whether the thread object is already in a broken state, but does not clear the status flag.

To break a thread by throwing an exception:

 Public classMyThreadextendsThread {@Override Public voidrun () {Try {             for(inti = 0; I < 500000; i++) {                if( This. Interrupted ()) {System.out.println ("It's already stopped!" I'm going to quit. "); Throw Newinterruptedexception (); } System.out.println ("I=" + (i + 1))); }        } Catch(interruptedexception e) {System.out.println ("Get into the catch in the Mythread.java class Run Method!" ");        E.printstacktrace (); }    }}

In addition, the Retuen method can also be used to break the thread. However, it is recommended to "throw exceptions" to implement a thread stop, as the exception can be thrown up in the catch block, allowing the thread to stop events to propagate.

6. Thread.yield () Method: Discard the current CPU resources and give it to other tasks to occupy CPU execution time. But the time to give up is uncertain, it is possible to just give up, and immediately get the CPU time slice.

7,setpriority () method: For the portability of the program, it is recommended to use Max_priority, norm_priority, min_priority three levels. Setting the priority does not mean that the lower priority is not called, but the CPU prefers to let the high priority execute first, but the CPU specifically calls that thread is not certain, the setting priority can only guarantee that the thread is called more frequently.

8,Setdaemon (true): Daemon thread. The daemon thread is a special thread, and its features have the meaning of "companionship", and the daemon thread automatically destroys when there is no non-daemon thread in the process. A typical daemon thread is a garbage collection thread, and when there is no non-daemon thread in the process, there is no need for the garbage collection thread to exist.

9. Join () Method: Wait for the thread to terminate. The join () method is basically to get the thread that invokes the method to complete the contents of the Run method, then execute the code after the join () method, and the call to the join () method can be interrupted by invoking the interrupt () method on the thread.

Vi. Other

1. The Stop () method is void: If forcing a thread to stop, it is possible that some cleanup work will not be completed. Another situation is that the locked object is "unlocked", resulting in data not synchronized processing, the problem of inconsistent data.

2,the Suspend () method pauses the thread.

3. The resume () method resumes the execution of the thread.

4, when using suspend () and resume (), if used improperly, it is very easy to cause the public synchronization object exclusive, so that other threads can not access the public synchronization object.

Multithreaded Programming Learning One (Java Multi-Threading Foundation)

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.