Thread of the life cycle of Java basic knowledge and relevant interview questions

A thread of the life cycle:
(1) Life cycle:
a thing from the moment of birth to the final in the middle of the whole process of death.
In the long life cycle of things, the experience is always different state (state infant / young people state / status of middle-aged / elderly status ...).
thread also has a life cycle, but also there are different states, transitions between each state.

(2) the definition of the API:
Here Insert Picture Description
(3) a graphical representation:
Here Insert Picture Description

1: a new state (new) Use to create a new thread object, only allocated on the heap memory space, under the new state, the thread they not start before the start method is called, there is just a thread object only .Thread t = new Thread ();. // This when t belongs to a new state when the thread object under a new state called the start method, this time from the New runnable state start the thread object method called only once, otherwise an error:. IllegalThreadStateException.
2: run state (Runnable) It is divided into two states, ready and running. Represent a ready state and run state. Ready state: after a call start method of the thread object, waits for the JVM scheduler (this thread is not running at this time) the operating state: Object obtained JVM thread scheduling, if there are a plurality of the CPU, it allows multiple threads to run concurrently.
3: blocking state (blocked) Running threads give up the CPU for some reason, temporarily stop operating, will enter the blocked state. At this JVM will not be assigned to the CPU thread, until the thread re-enter the ready state, have a chance to run the state. Blocking state can only first enter the ready state, not directly into the operational state of the two cases blocking state: 1): when a thread is in the process of running, trying to get genlock, B was at this time JVM thread gets saved to the current a thread. lock of the object in the pool, a thread into the blocked state. 2): when a thread is in the process of operation, the IO request is issued, this time into the blocked state.
4. Wait state (Waiting) (Wait state can only be awakened by other threads): wait no method parameters used in this case, when the thread is in the process of running, call the wait () method, the JVM at this time there is an object of the current thread waiting pool.
5: Timing wait state (timed waiting) (Sleep or wait method using a method with parameters) 1): When a thread is in the running process, called wait (long time) method, the presence of an object at this time JVM current thread to wait in the pool 2): ​​the current thread of execution sleep (long time) method.
6: final state (terminated) Commonly referred to as death state that the thread termination .1): Normal End run method exits (wrongful death) .2): After the exit (abnormal exception is encountered, the program is interrupted) (accidental death) .- thread upon termination, you can not restart the start, otherwise an error (IllegalThreadStateException) obsolete in thread class method (thread-safe because there is a problem, so deprecated):. void suspend (): pauses the current thread void resume (): the current recovery thread void stop (): the end of the current thread

Interview questions: What are the state of the thread? Transfer state are dependent on what method?
A: All status and operating status are (Runnable) transferred in
1: new state (new new) (call start method runnable)
2: runnable (Runnable)
① parameters used in this case no wait method enters the wait state (waiting)
② (sleep or wait method using a method with parameters, a wait state into the timer
3: blocking state (blocked)
4. wait state (waiting) (method can only be used by other threads or notify the method notifyAll wake runnable)
5: timer waiting state (timed waiting) (a predetermined time to the time parameter)
6: end state (terminated)

Two sleeping threads:
thread sleep: execution thread to pause for some time, the timing to enter the wait state.
Methods: static void sleep (long millis)
call sleep, give up the current thread CPU, within a specified time period, sleep where the thread does not get a chance to execute.
Thread in this state will not release the synchronization lock / sync listener.
The method more used to simulate network delay, so that multiple threads concurrently access the same mistake more obvious effects of a resource.
Will deliberate use of this method in development

III. Joint thread (the Join)
the Join method represents a thread after thread wait for another thread to complete execution. After the join method is called, the thread object is blocked.
This is called also the joint thread, that thread is the current thread and the thread where the current combined into a single thread.

class join extends Thread{
    @Override
    public void run() {
        for(int i =0;i<50;i++){
            System.out.println("join"+i);
        }
    }
}
public class JoinDemo {
    public static void main(String[] args) throws InterruptedException {
        join join = new join();
        for(int i =0;i<50;i++){
            if(i==10){
                join.start();
            }
            if(i==20){
                join.join();
            }
            System.out.println("main"+i);
        }
    }
}

Four background thread:
the thread running in the background, its purpose is to provide services to other threads, also known as the "guardian of the thread." JVM's garbage collection thread is a typical background thread.
Features: If all foreground threads have died, automatic background thread death, foreground thread is not over, a background thread is not the end.
Whether the test object is a background thread thread: Use thread.isDaemon ().
When the foreground thread thread is created in the default foreground thread, it can be set to a background thread by setDaenon (true) method, and if and only if the new thread a background thread is created, a new thread is a background thread.
Set background thread: thread.setDaemon (true), the process must start before the method call, otherwise IllegalThreadStateException appear abnormal.

V. thread group and the timer
provided in the JDK java.util package Timer class, can be timed to perform particular tasks.
The TimerTask class represents a task performed by the timer.
Common methods:
Schedule (the TimerTask Task, Long Delay, long period): Schedules the specified task from the start after a specified delay for repeated fixed-delay execution.
schedule (TimerTask task, long delay) : Schedules the specified task at the specified time

public class TimerDemo {
    public static void main(String[] args) {
        System.out.println("begin....");
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(new Date().toLocaleString());
            }
        },3000,1000);
    }
}

The output:
Here Insert Picture Description
of ThreadGroup class represents a thread group, may be centralized management of a set of threads.
User when creating a thread object, you can specify the thread group to which it belongs by the constructor.
The Thread (of ThreadGroup Group, String name);
if A thread creates B thread, thread B if the packet is not set, then B is added to the thread group a thread thread.
Once a thread group to join a thread, the thread has been present in the thread group until the thread dies, you can not modify the thread in the middle of packet.
when the Java program is running, JVM will create a group called main thread, by default, all threads are changed under the thread group.

Published 99 original articles · won praise 2 · Views 2614

Guess you like

Origin blog.csdn.net/weixin_41588751/article/details/105229730