Getting Started with Java multithreading

Source: Internet
Author: User
Tags thread class

One, multi-tasking, multi-process, single-threaded, multi-threaded to understand the multi-threaded from the operating system of the principle of speaking.   formerly the old DOS operating system (V 6.22) is a single task, there is no concept of threading, the system can only do one thing at a time. For example, you can't rename the file name when you copy something. In order to improve the utilization efficiency of the system, batch processing is used to perform the task in batches.   Now the operating system is a multitasking operating system, each running task is the operating system to do one thing, such as you listen to the song while still using MSN and friends chatting. Listening to songs and chatting are two tasks, both of which are carried out "at the same time." A task typically corresponds to a process, or it may contain several processes. For example, a running MSN will correspond to an MSN process, and if you are using a Windows system, you can see the process information that the operating system is running in Task Manager.   Generally, when you run an application, you start a process, and some of course start multiple processes. When the process is started, the operating system allocates resources to the process, the most important of which is memory space, because the program runs in memory. In the process, some program flow blocks can be executed in a random order, and the code block can be executed multiple times at the same time. In fact, such blocks of code are thread bodies. A thread is a code flow that is executed in a process in a disorderly order. This execution pattern becomes concurrent execution when multiple threads are running concurrently.   Multi-Threading is designed to maximize CPU resource utilization.  java programs are run in a Java Virtual machine (JVM), and within the JVM, the multitasking of the program is done through threads. Starting a Java application with Java commands starts a JVM process. In the same JVM process, there is only one process, which is itself. In this JVM environment, all program code runs as threads.   Generally common Java applications are single-threaded. For example, when running a Java application with a Java command of the simplest HelloWorld, a JVM process is started, the JVM finds the program's entry point, Main (), and then runs the main () method, which creates a thread called the main thread. When the main method finishes, the main thread runs. The JVM process also exits.   For more than one thread in a process, multiple threads share the memory block of a process, and when a new thread is generated, the operating system does not allocate new memory, but instead lets the new thread share the memory of the original process block. As a result, communication between threads is easy and fast. Because different processes are in different chunks of memory, communication between processes is relatively difficult.   In fact, the multi-process of the operating system realizes multi-task concurrent execution, the multithreading of the program realizes the concurrent execution of the process. Multi-task, multi-process, multi-threaded premise is to require the operating system to provide multi-tasking, multi-process, multi-threaded support.   In Java programs, the JVM is responsible for thread scheduling. Thread scheduling is a value that assigns the use of CPU to multiple threads according to a specific mechanism. There are two kinds of scheduling modes: time-sharing scheduling and preemptive scheduling. The time-sharing scheduling is that all threads take turns to gain CPU access and evenly allocate the CPU per thread, and preemptive scheduling is based on the priority level of the thread to obtain the CPU's right to use. The JVM's thread-scheduling pattern employs a preemptive pattern.   The so-called "concurrent execution" and "simultaneous" are not really "simultaneous" in real sense. As we all know, the CPU has a clock frequency, indicating the number of times per second The CPU instructions can be executed. In each clock cycle, the CPU can actually only execute one (and possibly many) instructions. The operating system manages the process threads, and in turn (without a fixed order) allocates each process a short period of time (not necessarily evenly distributed), and then within each thread, the program code handles the internal thread's time allocation itself, switching between threads to execute, and the switching time is very short. So multitasking, multi-process, multi-threading is a kind of macroscopic feeling of the operating system, from the microscopic point of view, the operation of the program is executed asynchronously.   in a word to summarize: Although the operating system is multithreaded, but the CPU can only do one thing at a time, and the human brain is the same, hehe.    Two, Java and multi-threaded  java language multithreading requires operating system support. The  java virtual machine allows an application to run multiple execution threads concurrently. The Java language provides extensibility points for multithreaded programming and gives a powerful threading control API.   in Java, multithreading is implemented in two ways: The extended Java.lang.Thread class implements the Java.lang.Runnable interface    each thread has a priority, and the execution of the high-priority thread takes precedence over the low-priority thread. Each thread can or cannot be marked as a daemon. When code running in a thread creates a new thread object, the initial priority of the new thread is set to the priority of the thread being created, and the new thread is the daemon only if the creation thread is the daemon thread.   When a Java virtual machine starts, it usually has a single non-daemon thread (which typically invokes the main method of a specified class). The Java virtual opportunity continues to execute the thread until any of the following conditions occur:  calls the Exit method of the runtime class, and the security Manager allows the exit operation to occur. All threads that are not daemon threads have stopped running, either through theReturned from a call to the Run method, or by throwing an exception that is propagated beyond the Run method.    extension Java.lang.Thread class  /** * File name:   testmitithread.java * Created by:   IntelliJ idea. * copyright:   Copyright (c) 2003-2006 * company:     Lavasoft ( [url]http://lavasoft.blog.51cto.com/[/url])  * author:      leizhimin * modifier:    leizhimin * Date time:   2007-5-17 10:03:12 * Readme :      multithreading  */public class Testmitithread {    public by extending the thread class static void Main (string[] rags) {        System.out.println (thread.currentthread (). GetName () + "thread run start!");         new Mitisay ("A"). Start ();        New Mitisay ("B"). Start ();        System.out.println (Thread.CurrentThread (). GetName () + "Thread run end!");   &nbsp }} class Mitisay extends Thread {    public Mitisay (String threadname) {    & nbsp;   Super (ThreadName);   }     public void run () {         System.out.println (GetName () + "thread run start!");         for (int i = 0; i < ten; i++) {       & nbsp;    System.out.println (i + "" + GetName ());             Try {                 Sleep ((int) math.random () *);           } catch ( Interruptedexception e) {                 E.printstacktrace ();           }        }        System.out.println (getName () + "Thread run end!");    }}  Run Result:  main thread run start!main thread run end! A thread Run starts! 0 A1 AB thread run start! 2 A0 B3 A4 A1 B5 A6 A7 A8 A9 AA thread run end!2 B3 B4 B5 B6 B7 B8 B9 BB thread Run End!  Description: Program startup run main time, Java The virtual machine starts a process, and the main thread is created at the main () call. With the Start method of the two objects that call Mitisay, another two threads are also started, so that the entire application runs under multiple threads.   Call the Thread.CurrentThread (). GetName () method in a method to get the name of the current thread. This method is called in the Mian method and gets the name of the main thread.   NOTE: Instead of executing multithreaded code immediately after the call to the start () method, the thread becomes operational (Runnable) and when it is run is determined by the operating system. The results from the running of the program can be found that multi-threaded programs are executed in a disorderly order. Therefore, only code that executes in a disorderly order is necessary to be designed as multithreaded. The purpose of the Thread.Sleep () method call is to not allow the current thread to occupy the CPU resources acquired by the process alone to allow a certain amount of time for other threads to execute. Virtually all multithreaded code execution sequences are indeterminate, and the results of each execution are random.    implement Java.lang.Runnable interface  /** * realize multithreading  */public class TestMitiThread1 by implementing Runnable interface Implements Runnable {     public static void Main (string[] args) {     & nbsp;  System.out.println (Thread.CurrentThread (). GetName () + "thread run start!");         TestMitiThread1 test = new TestMitiThread1 ();        Thread Thread1 = new Thread (test);        thread thread2 = new thread (test);   & nbsp;     Thread1.start ();        Thread2.start ();         System.out.println (Thread.CurrentThread (). GetName () + "Thread run end!");    }     public void run () {        System.out.println (Thread.CurrentThread (). GetName () + "thread run start!");         for (int i = 0; i < ten; i++) {       & nbsp;    System.out.println (i + "" + Thread.CurrentThread (). GetName ());             Try {                 Thread.Sleep ((int) Math.random () *);           } catch ( Interruptedexception e) {                 E.printstacktrace ();           }        }        System.out.println ( Thread.CurrentThread (). GetName () + "Thread run end!");    }}  Run Result:  main thread run start! Thread-0 thread runs start!main thread runs end!0 thread-0thread-1 thread runs! 0 Thread-11 Thread-11 Thread-02 Thread-02 Thread-13 Thread-03 Threa d-14 Thread-04 Thread-15 Thread-06 Thread-05 Thread-17 Thread-08 Thread-06 Thread-19 Thread-07 thread-1thread-0 thread run end!8 T hread-19 thread-1thread-1 Thread Run end!  Description: The TestMitiThread1 class has the characteristics of multithreaded classes by implementing the Runnable interface. The run () method is a convention for multi-threaded procedures. All multithreaded code is inside the Run method. The thread class is actually a class that implements the Runnable interface. At the start of multithreading, you need to construct the object through the thread class's construction method, thread (Runnable target), and then call the start () method of the thread object to run the multithreaded code. Actually all the moreThread code is run by running the thread's start () method. Therefore, whether you are extending the thread class or implementing a runnable interface to implement multi-threading and ultimately control threading through the API of the thread's object, the API familiar with the thread class is the basis for multithreaded programming.   V. Read the thread class api static int max_priority          The highest priority a thread can have. The static int min_priority          the lowest priority that a thread can have. The static int norm_priority          The default priority assigned to the thread.   Constructor Method Summary thread (Runnable target)           assigns a new thread object. Thread (String name)           assigns a new thread object.    method Summary static Thread CurrentThread ()           Returns a reference to the currently executing thread object.  classloader getcontextclassloader ()           Returns the context of the thread ClassLoader.  long getId ()           returns the identifier of the thread.  string GetName ()           Returns the name of the thread.  int getpriority ()           returns the priority of the thread.  thread.state getState ()           returns the state of the thread.  threadgroup getthreadgroup ()           returns the thread group to which the thread belongs. Static Boolean Holdslock (Object obj)           if and only if the front thread maintains a monitor lock on the specified object, To return True.  void interrupt ()           break thread. Static Boolean interrupted ()           tests if the front thread has been interrupted.  boolean isAlive ()           test thread is active.  boolean Isdaemon ()           tests whether the thread is a daemon thread.  boolean isinterrupted ()           test thread has been interrupted.  void join ()           waits for the thread to terminate.  void join (Long Millis)           waits for the thread to terminate for a maximum of millis milliseconds.  void Join (long millis, int nanos)           wait for the thread to terminate for a maximum of millis milliseconds + Nanos nanoseconds.  void Resume ()           is obsolete. This method is only used with suspend (), but suspend () has been objected to because it has a deadlock tendency. For more information, see why Thread.stop, Thread.Suspend and Thread.Resume have been objected to?  void run ()           call this Runnable if the thread is constructed using a standalone Runnable run object The Run method of the object, otherwise, the method performs no action and returns.  void Setcontextclassloader (ClassLoader cl)           Set the context of the thread ClassLoader.  void Setdaemon (Boolean on)           marks the thread as either a daemon thread or a user thread. static void Setdefaultuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh)            sets the default handler that is called when a thread is abruptly terminated because it did not catch an exception, and no other handlers are defined for the thread.  void setName (String name)           change the thread name so that it is the same as the parameter name.  void setpriority (int newpriority)           Change the priority of the thread.  void Setuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh)            sets the handler that is called when the thread terminates abruptly because the exception was not caught. static void sleep (long Millis)           allow the currently executing thread to hibernate (suspend execution) for a specified number of milliseconds. static void sleep (long millis, int nanos)           Sleeps (suspends execution) the currently executing thread in the specified number of milliseconds plus the specified number of nanoseconds.  void start ()           causes the thread to execute, and the Java virtual machine calls the thread's Run method.  void Stop ()           is obsolete. This method has inherent insecurity. Terminating a thread with Thread.stop frees all monitors it has locked (as a natural consequence of unchecked threaddeath exceptions that propagate up the stack). If any objects previously protected by these monitors are in an inconsistent state, the corrupted object will be visible to other threads, which may cause arbitrary behavior. Many uses of stop should be replaced by code that modifies only certain variables to indicate that the target thread should stop running. The target thread should check the variable periodically, and if the variable indicates that it is going to stop running, return from its run method. If the target thread waits for a long time (for example, based on a condition variable), you should use the interrupt method to interrupt the wait. For moreFor more information, see Why do you disapprove of using Thread.stop, Thread.Suspend, and Thread.Resume? 》。  void Stop (Throwable obj)           is obsolete. This method has inherent insecurity. See Stop () for more information. The additional danger of this method is that it can be used to generate exceptions that the target thread is not prepared to handle (including checked exceptions that the thread is less likely to throw if the method is not available). For more information, see why Thread.stop, Thread.Suspend and Thread.Resume have been objected to?  void suspend ()           is obsolete. The method has been objected to because of its inherent deadlock tendency. If the target thread is suspended and there is a lock on the monitor that secures the critical system resources, no thread can access the resource until the target thread restarts. If the thread that is restarting the target thread wants to lock the monitor before calling resume, a deadlock occurs. This type of deadlock usually proves itself to be a "frozen" process. For more information, see why Thread.stop, Thread.Suspend and Thread.Resume have been objected to?  string toString ()           returns the string representation of the thread, including the thread name, priority, and thread group. static void yield ()           pauses the currently executing thread object and executes other threads.    The state transition diagram of a thread   thread under certain conditions, the state changes. The state transition diagram for thread changes is as follows:  1, new State (new): A newly created thread object. 2. Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used. 3, running State (Running): The ready state of the thread gets the CPU, executes the program code. 4. Blocking status (Blocked): A blocking state is a time when a thread abandons the CPU for some reason and temporarily stops running. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking: (i), waiting for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool. (ii), synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread. (iii), other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state. 5. Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.    thread scheduling 1, thread prioritization: Java threads have priority, high-priority threads get more running opportunities. The priority of a  java thread is expressed in integers, and the value range is the following three static constants for the 1~10,thread class: Static int max_priority       The     thread can have the highest priority, with a value of 10. The static int min_priority          thread can have the lowest priority, with a value of 1. The static int norm_priority          The default priority assigned to the thread, with a value of 5. The SetPriority () and GetPriority () methods of the  thread class are used to set and get the priority of the thread, respectively.   Each thread has a default priority. The default priority for the primary thread is thread.norm_priority. The priority of a thread has an inheritance relationship, such as the B thread created in a thread, then B will have the same priority as a. The JVM provides 10 thread priorities, but does not map well with common operating systems. If you want the program to be portable to each operating system, you should only use the thread class with the following three static constants as priority, which ensures that the same precedence is used for the same scheduling. &NBSP;2, Thread sleep: thread.sleep (Long Millis) method, so that the lineTo the blocking state. The Millis parameter sets the time to sleep, in milliseconds. When sleep is over, it becomes ready (Runnable) state. Sleep () platform portability is good.  3, thread wait: The Wait () method in the object class causes the current thread to wait until the other thread calls the Notify () method of this object or the Notifyall () Wake method. This two wake-up method is also a method in the object class, and behaves equivalent to calling wait (0).  4, thread Concession: the Thread.yield () method pauses the currently executing thread object, giving the execution opportunity to the same or higher priority thread.  5, thread join: Join () method, wait for other threads to terminate. Invoking the Join () method of another thread in the current thread, the current thread goes into a blocking state until the other process finishes running, and the current thread is then turned into a ready state by blocking.  6, Thread Wake: The Notify () method in the object class, which wakes up a single thread waiting on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods. Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object. A similar approach also has a notifyall () that wakes up all the threads waiting on this object monitor.   NOTE: Thread suspend () and resume () Two methods have been abolished in JDK1.5 and are no longer introduced. Because there is a deadlock tendency.  7, common thread nouns explain the main thread: the threads generated by the JVM Invoker Mian (). Current thread: This is an easy-to-confuse concept. Generally refers to the process obtained through Thread.CurrentThread (). Background thread: Refers to a thread that provides services to other threads, also known as a daemon thread. The garbage collection thread of the JVM is a background thread. Foreground thread: Refers to the thread that accepts the background thread service, in fact the foreground background thread is linked together, just like the puppet and the behind-the-scenes manipulator's relationship. The Puppet is the foreground thread and the behind-the-scenes manipulator is a background thread. The thread created by the foreground thread is also the foreground thread by default. You can use the Isdaemon () and Setdaemon () methods to determine and set whether a thread is a background thread.   Reproduced as: http://lavasoft.blog.51cto.com/62575/27069/     The Small series oneself summarizes: 1. Thread is asynchronous access, can be timed trigger, can set priority
2. For cup, in fact, the same moment is still just one thing to do3. Use threads in Java to implement the Runnable interface and inherit the thread class4. Methods commonly used in threading include the above-mentioned

Getting Started with Java multithreading

Related Article

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.