Ali P8 former architect summary of some of Java on multithreaded programming experience Shu dry

First, recognize that multi-tasking, multi-process, single-threaded, multi-threaded

To recognize that we must start with the principle of multi-threaded operating system.

Before the old DOS operating system (V 6.22) is a single task, there is no concept of threads, the system can only do one thing. For example, you can not rename the file name when copy something. In order to improve the utilization efficiency of the system, the use of batch to batch tasks.

Current operating systems are multitasking operating systems, each running the operating system's task is to do one thing, such as MSN and you still chat with friends while listening to music. Listen to music and chat are two tasks, the two tasks is "simultaneous" performed. A task usually corresponds to a process, and may also contain several processes. For example, to run MSN MSN corresponds to a process, if you are using a windows system, you can see the process running operating system information in the Task Manager.

In general, when an application is running, when it started a process, of course, some will start multiple processes. The boot process, the operating system will allocate resources for the process, the most important resource is the memory space, because the program is running in memory. In the process, some of the program flow block is out of order, and the block of code can be executed multiple times simultaneously. Indeed, such a block is the thread thereof. A thread is the code flow process order execution. When running multiple threads simultaneously, so the execution mode to be executed concurrently.

Multithreading purpose is to maximize the use of CPU resources.

Written in Java and runs in the Java Virtual Machine (JVM) in the inside of the JVM, multi-tasking program is implemented by a thread. Each launch a java application with java command, it will start a JVM process. In the same JVM process, and only one process, is its own. In this JVM environment, run all programs are based on the code thread to run.

General common Java applications are single-threaded. For example, when you run a simple HelloWorld Java application using the java command to start a JVM process, JVM to find the entry point main program program (), and then run the main () method, thus creating a thread, this thread called the main thread. After the end of the main method, the main thread runs to completion. JVM process also immediately withdraw.

For multiple threads in a process, the memory block multiple threads share the process, when a new thread is created, the operating system does not allocate new memory, but to a new thread shared memory block of the original process . Therefore, the communication between threads is easy, fast. Since different processes in different memory blocks, so that the communication between processes is relatively difficult.

In fact, multi-process operating system implements concurrent execution of multi-tasking, multi-threaded program implements concurrent execution process. Multi-tasking, multi-process, multi-threaded operating system premise is required to provide multi-tasking, multi-process, multi-thread support.

In Java programs, JVM is responsible for scheduling threads. Thread scheduling is the value assigned right to use the CPU for a plurality of threads in a particular mechanism.

There are two scheduling modes: time-sharing scheduling and preemptive scheduling. Time-sharing scheduling of all threads in turn obtain the right to use the CPU, and the average time each thread CPU-allocation; preemptive scheduling is to obtain the right to use the CPU based on the priority level of the thread. JVM thread scheduling mode uses a preemptive mode.

The so-called "concurrent execution", "simultaneously" in fact not "simultaneous" in the true sense. Is well known, the CPU has a clock frequency, expressed in number of instructions per second can be executed cpu. In each clock cycle, CPU really only to perform a (also more than likely) command. The operating system process thread management, in turn (there is no fixed order) assigning each process a short period of time (not necessarily the average), and then within each thread its own program code processing time of the process of internal threads distribution, switching between a plurality of threads to execute one another, the switching time is very short. So multi-tasking, multi-process, multi-threaded operating system are giving a macro feel, from the microscopic point of view, to run the program is executed asynchronously.

Do sum up in one sentence: Although the operating system is multi-threaded, but each CPU can only do one thing at a time, and the human brain is the same, huh, huh.

Two, Java and Multithreading

Multi-threaded Java language requires operating system support.

Java Virtual Machine allows an application to concurrently run multiple threads of execution. Java programming language provides a multi-threaded extension points, and gives a powerful thread control API.

In Java, multi-threaded in two ways:

  • Extended java.lang.Thread class
  • Implement the interface java.lang.Runnable

Each thread has a priority, the implementation of high-priority thread priority to low priority thread. Each thread may or may not marked as a daemon. When the code running in some thread creates a new Thread object, the initial priority of the new thread is set to create a thread priority, and if and only if the creating thread is a daemon thread, the new thread is a daemon .

When the Java virtual machine starts, usually have a single non-daemon thread (which typically calls the main method of a specified class). Java Virtual Machine continues to execute threads until such time as either of the following occurs:

It calls the exit method of class Runtime, and the security manager has permitted the exit operation occurs.

All threads of non-daemon threads have died, either by returning from the call to the run method, or a spread to the outside of the abnormal run method by throwing

Third, the expansion java.lang.Thread class

<pre>
 / ** 
 * File the Name: TestMitiThread.java 
 * the Created by:. IntelliJ IDEA 
 * Copyright: Copyright (C) 2003-2006 
 * Company: Lavasoft ([URL] http://lavasoft.blog.51cto.com/ [/ URL]) 
 * the Author: leizhimin 
 * Modifier: leizhimin 
 * a Date Time: 2007-5-17 10:03:12 
 * the Readme: multi-threaded by extending the thread class 
 * / 
public  class TestMitiThread {
     public  static  void main (String [ ] Rags) { 
        System.out.println (Thread.currentThread () getName (). + "operation start thread!" );
         new new MitiSay ( "A" ) .start ();
         new new MitiSay("B").start();
        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
    }
}
class MitiSay extends Thread {
    public MitiSay(String threadName) {
        super(threadName);
    }
    public void run() {
        System.out.println(getName() + " 线程运行开始!");
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + getName());
            try {
                sleep((int) Math.random () * 10 ); 
            } 
            the catch (InterruptedException E) { 
                e.printStackTrace (); 
            } 
        } 
        System.out.println (getName () + "end of the thread run!" ); 
    } 
}
 </ Pre>

operation result:

main thread running start! 
end of the main thread running ! 
A thread running start ! 
0 A
 . 1 A 
B thread running start ! 
2 A
 0 B
 . 3 A
 . 4 A
 . 1 B
 . 5 A
 . 6 A
 . 7 A
 . 8 A
 . 9 A 
end A thread running ! 
2 B
 . 3 B
 . 4 B
 . 5 B
 . 6 B
 . 7 B
 . 8 B
 . 9 B 
B thread end of run !

Description:

Main program starts running time, java virtual machine to start a process, the main thread main () call when they were created in the main. With the start method is called two objects MitiSay, the other two threads have started, so that the entire application to run in multi-threaded.

In a call Thread.currentThread method (). GetName () method, you can get the name of the current thread. This method is called mian method, the acquisition is the name of the main thread.

Note: After calling start () method is not executed immediately multi-threaded code, but so that the thread becomes runnable (Runnable), when to run is determined by the operating system.

It is found from the results of running, multi-threaded program is out of order. Therefore, the code is only necessary to have the order execution designed for multi-threading.

Thread.sleep () method call purpose is to keep the current thread occupy CPU resources obtained by the process alone, to set aside a certain time for opportunities in other threads of execution.

Virtually all multithreaded code execution order is uncertain, the result of each execution is random.

Fourth, implement the interface java.lang.Runnable

<pre>
/**
 * 通过实现 Runnable 接口实现多线程
 */
public class TestMitiThread1 implements Runnable {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
        TestMitiThread1 test = new TestMitiThread1();
        Thread thread1 = new Thread(test);
        Thread thread2 = new Thread(test);
        thread1.start();
        thread2.start();
        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
    }
    public void run() {
        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + Thread.currentThread().getName());
            try {
                Thread.sleep((int) Math.random() * 10);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "End thread runs!" ); 
    } 
}
 </ Pre>

operation result:

main thread running start! 
the Thread -0 thread running start! 
main thread running end ! 
0 the Thread-0 
the Thread -1 threads running start! 
0-the Thread. 1 
. 1. 1-the Thread 
. 1 the Thread-0 
2 0 the Thread- 
2. 1-the Thread 
. 3 the Thread -0 
. 3. 1-the thread 
. 4 the thread-0 
. 4-the thread. 1 
. 5 the thread-0 
. 6 the thread-0 
. 5-the thread. 1 
. 7 the thread-0 
. 8 the thread-0 
. 6-the thread. 1 
. 9 the thread-0 
. 7. 1 the thread- 
the thread -0 thread run end! 
. 8. 1-the thread 
. 9. 1 the thread- 
the thread the end of the thread run -1!

Description:

TestMitiThread1 class by implementing Runnable interface, characterized in that with such a multi-threaded type. run () method is a convention multithreaded programs. All multithreaded code in the run method inside. Thread class is actually a class that implements the Runnable interface.

At startup multithreading, we need to construct objects through the Thread class constructor Thread (Runnable target), and then call the object's start Thread () method to run multithreaded code.

Virtually all multi-threaded code is by start () method of the Thread run to run. Therefore, whether or extend the Thread class 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.

V. Reading Thread class API

  • static int MAX_PRIORITY: a thread can have the highest priority.
  • static int MIN_PRIORITY: a thread can have the lowest priority.
  • static int NORM_PRIORITY: assigned to a thread default priority.

Constructor Summary

  • Thread (Runnable target): Allocates a new Thread object.
  • Thread (String name): Allocates a new Thread object.

Method Summary

  • static Thread currentThread (): Returns a reference to the currently executing thread object is.
  • ClassLoader getContextClassLoader (): Returns the context ClassLoader this thread.
  • long getId (): Returns the identifier of the thread.
  • String getName (): Returns the name of this thread.
  • int getPriority (): Returns the thread's priority.
  • Thread.State getState (): Returns the status of the thread.
  • ThreadGroup getThreadGroup (): Returns the thread group to which the thread belongs.
  • static boolean holdsLock (Object obj): if and only if the current thread holds the monitor lock on the specified object, it returns true.
  • void interrupt (): interrupt thread.
  • static boolean interrupted (): test whether the current thread has been interrupted.
  • boolean isAlive (): Tests if this thread is active.
  • boolean isDaemon (): Tests if this thread is a daemon thread.
  • boolean isInterrupted (): Tests if this thread has been interrupted.
  • void join (): Waits for this thread.
  • void join (long millis): this thread is waiting for the longest millis milliseconds.
  • void join (long millis, int nanos): this thread is waiting for the longest millis milliseconds + nanos nanoseconds.
  • void resume (): Obsolete. This method uses only suspend () together, but suspend () has been deprecated because it is deadlock-prone. For more information, see Why Thread.stop, Thread.suspend and Thread.resume was opposed? .
  • void run (): If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is invoked; otherwise, this method does nothing and returns.
  • void setContextClassLoader (ClassLoader cl): set the context ClassLoader the thread.
  • void setDaemon (boolean on): this thread is marked as a daemon thread or a user thread.
  • static void setDefaultUncaughtExceptionHandler (Thread.UncaughtExceptionHandler eh): Set when the thread due uncaught exception terminates abruptly, and does not define a default processing routine called by other processes for the thread.
  • void setName (String name): change the name of this thread equal to the argument name.
  • void setPriority (int newPriority): Changing thread priority.
  • void setUncaughtExceptionHandler (Thread.UncaughtExceptionHandler eh): Set the handler invoked when due to an uncaught exception abrupt termination of the thread.
  • static void sleep (long millis): the currently executing thread to sleep in a specified number of milliseconds (suspended).
  • static void sleep (long millis, int nanos): the currently executing thread to sleep in a specified number of milliseconds plus the specified number of nanoseconds (suspended).
  • void start (): Causes this thread to begin execution; Java Virtual Machine calls the run method of this thread.
  • void stop (): Obsolete. This method is inherently unsafe. With Thread.stop terminate the thread releases all the monitors that it has locked (as unchecked propagation along the stack upwardly a natural consequence ThreadDeath exception). If any objects previously protected by these monitors were in an inconsistent state, the damaged objects visible to other threads, which may lead to arbitrary behavior. Many uses of stop should be the only modifies some variable to indicate that the target thread should stop running code to replace. The target thread should check this variable regularly, and if the variable indicates that it wants to stop the run, in order to return from its run method. If the target thread waits for a long time (for example based on a condition variable), the interrupt method should be used to interrupt the wait. For more information, see "Why not in favor of using Thread.stop, Thread.suspend and Thread.resume? . "
  • void stop (Throwable obj): Obsolete. This method is inherently unsafe. See stop () for more information. Additional danger of this method is that it can be used to generate an abnormal target thread preparation process (including the process if there is no abnormality has checked the thread is less likely to be thrown). For more information, see Why Thread.stop, Thread.suspend and Thread.resume was opposed? .
  • void suspend (): Obsolete. This method has been deprecated, as it is inherently deadlock-prone. If the target thread hangs on the monitor to protect critical system resources to maintain a lock, then the target thread resumes before any thread can access this resource. If you restart the target thread thread want to lock this monitor prior to calling resume, deadlock occurs. Such deadlocks typically manifest themselves as "frozen" processes. For more information, see Why Thread.stop, Thread.suspend and Thread.resume was opposed? .
  • String toString (): Returns a string representation of the thread, including the name of a thread, and thread priority group.
  • static void yield (): pause the currently executing thread object, and perform other threads.

Sixth, the thread state transition diagram

Thread under certain conditions, the status will change. Thread changes state transition diagram as follows:

  1. New state (New): create a new thread object.
  2. Ready state (Runnable): After the thread object is created, other thread calls the start () method of the object. The state of the thread runnable threads in the pool is located, has become runnable, waiting to acquire the right to use the CPU.
  3. Running state (Running): ready state of the thread gets the CPU, executes the program code.
  4. Blocked (Blocked): the thread is blocked for some reason to give up the right to use CPU temporarily stops running. Until the thread into the ready state, a chance to go running. Case of obstruction of three categories:
    • Waiting for blocking: running thread execution wait () method, JVM will thread into the wait pool.
    • Synchronous blocking: threads running at the time of acquiring synchronization lock object, if the synchronization lock is occupied by another thread, the JVM will lock into the thread pool.
    • Other blocking: a thread of execution sleep () or join () method, or issue the I / O request, the JVM will set the thread is blocked. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.
  5. Death state (Dead): thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle.

Seven, thread scheduling

1, adjust thread priority: Java thread priority and high-priority thread will get more chance to run.

Java thread priority is represented by an integer, the range is 1 ~ 10, Thread class has three static constants:

  • static int MAX_PRIORITY: a thread can have the highest priority, the value is 10.
  • static int MIN_PRIORITY: a thread can have the lowest priority value of 1.
  • static int NORM_PRIORITY: assigned to a thread default priority value of 5.

Thread class the setPriority () and getPriority () method are used to set and retrieve the priority of the thread.

Each thread has a default priority. The default priority of the main thread is Thread.NORM_PRIORITY.

Thread priority inheritance relationship, such as A thread creates a thread B, then A and B will have the same priority.

JVM offers 10 thread priorities, but with common operating systems are not well mapped. If the desired program can be transplanted to each operating system should only be used following three Thread class static constant as the priority, this will ensure that the same priority scheduling mode using the same.

2, thread to sleep: Thread.sleep (long millis) method, the thread to blocking state. millis parameter setting sleep time in milliseconds. After the end of sleep, it turned Ready (Runnable) state. sleep () platform portability is good.

3, the thread waits: Object class wait () method causes the current thread to wait until another thread invokes the object's notify () method or the notifyAll () wake-up method. The two wake-up method is a method of the Object class, the behavior is equivalent to calling wait (0) the same.

4, thread concessions: Thread.yield () method, pause the currently executing thread object, to give the opportunity to perform the same or a higher priority thread.

5, thread added: join () method, wait for the other thread to terminate. Call another thread in the current thread join () method, the current thread into the blocked state, until the end of another process to run, and then by blocking the current thread into the ready state.

6, thread wakes: notify Object class () method, a single thread wake monitor waiting on this object. If all threads are waiting on this object will be selected wake up one thread. Choice is arbitrary and occurs when a decision on implementation. A thread wait method to wait on an object's monitor by calling them. Until the current thread to give up the lock on this object, in order to continue execution thread to be awakened. The awakened threads will compete with the conventional way all the other threads on the object actively synchronized; for example, awakened thread no reliable privilege or disadvantage in terms of as a thread to lock this object. There is also a similar method notifyAll (), wakes up all threads waiting on this object's monitor.

Note: Thread the suspend () and resume () method has been abolished in two JDK1.5 in, no longer introduced. Because there is deadlock-prone.

7, the common thread Glossary

  • The main thread: JVM caller mian () thread produced.
  • Current thread: This is a confusing concept. Generally refers to the process to get through Thread.currentThread ().
  • Background thread: that thread to provide services to other threads, also known as a daemon thread. JVM's garbage collection thread is a background thread.
  • Foreground thread: is the thread a background thread to accept the service, in fact, foreground to background threads are linked together like a puppet and behind the scene the same relationship. Puppet is the foreground thread, it was secretly a background thread. Threads created by the default foreground thread is the foreground thread. It can be determined by isDaemon () and setDaemon () method and a thread is provided as a background thread.

Su ii: focus on research and knowledge of Java development technologies to share!

————END————

Recommended reading]

Java programmers prepare for the "Golden September and Silver October," the necessary interview skills (Java attached Ctrip post interview questions)

Guess you like

Origin www.cnblogs.com/Java-no-1/p/11370319.html