A, java multithreading summarize the basics

First, the difference between threads and processes

1. The thread is actually an execution path, the application process is a stand-alone application.

2. A thread is a path of execution, multiple execution paths executed simultaneously, in the process, there will be N multiple threads, processes the set of all threads.

3. Use the multi-threaded purpose is to improve program efficiency.

Second, create a multi-threaded approach (following three methods are not one by one example)

1. The first is a Thread class inheritance, override the run method.

2. Implement Runnable interface, override the run method.

3. Use an anonymous inner classes.

Third, the daemon thread

1.java in two threads, one is the user thread, the other is the guardian of the thread.

1.1 User thread refers to user-defined threads created, the main thread to stop, will not stop user threads.

1.2. Daemon thread when the process does not exist or stop the main thread, the thread daemon will be stopped.

2. Use setDaemon (true) method to set a daemon thread

3. Code Example

public class DaemonThread {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    System.out.println("我是子线程...");
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {

            }
            System.out.println("我是主线程");
        }
        System.out.println("主线程执行完毕!");
    }
}

4. Results

4.1 Set Thread . SetDaemon ( to true ), the following results:

我是子线程...
我是主线程
我是子线程...
我是主线程
我是子线程...
我是主线程
主线程执行完毕!

4.2 does not set the Thread . SetDaemon ( to true ), the following results (I was a child thread ... (has been circulating)):

我是子线程...
我是主线程
我是子线程...
我是主线程
我是子线程...
我是主线程
主线程执行完毕!
我是子线程...
我是子线程...
我是子线程...

Fourth, multi-threaded operating status

1. Picture resolve

Thread from creation, always run to the end in one of the following five states: New state, ready state, running state, blocking state and the state of death.

2. each state analysis

2.1 New State: When a thread is created with the new operator, for example, new Thread (r), the thread has not started to run, in this case a new thread state. When a thread is in the nascent state, the program code that has not yet started running thread

2.2 ready state: a newly created thread does not start automatically, to execute thread, the thread must call the start () method. When calling thread object start () method to start a thread that is, create a system resource threads running start () method, and schedule threads run run () method. After the start () method returns, the thread is in the ready state. Thread a state of readiness does not necessarily run immediately run () method, the thread must also compete with other thread CPU time, CPU time before they can obtain only running thread. Because a single CPU in a computer system, it is impossible to run multiple threads simultaneously, one time only one thread is running. Therefore, at this time there may be multiple threads in the ready state. Multiple threads in the ready state is determined by the Java runtime system thread scheduler ( the Thread Scheduler ) to schedule.

2.3 operating status: When the thread gets CPU time, before it went into operation, really started run () method.

2.4 blocked state: the thread during operation, may enter the blocked state due to various reasons:
        1> thread to sleep by calling the method sleep;
        2> a calling thread is blocked on I / O operations, i.e., the input operation output operation will not return to it until the completion of the caller;
        3> thread trying to get a lock, but the lock is being held by another thread;
        4> thread is waiting for a trigger condition;

2.5 Death Status: There are two reasons why the thread death:
       1) RUN method exits normally and natural death.
       2) an uncaught exception terminates the thread run method sudden death.
In order to determine whether the current thread alive (that is, either can be run either be blocked), use isAlive method. If you are running or blocked, it returns true; if the thread is still new and not run the state, or the death of a thread, false is returned.

Five, join () method

1. For example: when performing the t1.join () method in which the main thread, the main thread that it should give the execution right t1.

2. Code Case:

public class DaemonThread {
    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {

                    }
                    System.out.println(Thread.currentThread().getName() + "i:" + i);
                }
            }
        });
        t1.start();
        // 当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1
        t1.join();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {

            }
            System.out.println("main" + "i:" + i);
        }
    }
}

3. Results

Thread-0i:0
Thread-0i:1
Thread-0i:2
Thread-0i:3
Thread-0i:4
Thread-0i:5
Thread-0i:6
Thread-0i:7
Thread-0i:8
Thread-0i:9
maini:0
maini:1
maini:2
maini:3
maini:4
maini:5
maini:6
maini:7
maini:8
maini:9

4. Analysis: The first child thread is finished, the main thread concessions, then execute the main thread after the completion of the implementation of the sub-thread.

Six small welfare

1. processes and threads difference?

 A: The process is the set of all threads, each thread is a path of execution process, but a thread execution path.

2. Why use multithreading?

 A: The program to improve efficiency

3. Thread class inheritance is good or implement Runnable good interfaces?

 A: Runnable Interface is good, because implements the interface can continue to inherit. Thread class inheritance can not be inherited.

CONCLUSION OF THE

1. Showings article to explain the multi-thread safety problems and solutions.

2. persevering! ! ! Ha ha ha ha ~ ~ ~

 

Published 122 original articles · won praise 64 · views 50000 +

Guess you like

Origin blog.csdn.net/chenmingxu438521/article/details/103760703