Java thread class

Basics

Thread State

According Thread.State class description, Java thread has six states: NEW, RUNNABLE, WAITING, TERMINATED, BLOCKED.

Ready state (NEW): When a thread object to call the start () method after the thread into the ready state. Ready thread in the ready queue, waiting to schedule the JVM thread scheduler.

Operating status (RUNNABLE): If the thread gets ready state of the CPU resources, you can perform run (), the thread will be running at this time. Thread running the most complex, it can become blocked state, ready state, and the state of death.

Blocked: If, after a thread executes sleep (sleep), wait (waiting) and other methods, the loss of occupied resources, the thread enters the blocked state from running. In the sleep time has come to get equipment or resources may re-enter the ready state. It can be divided into three types:

  • Waiting for blocking (the WAITING) : threads of execution running state of wait (), join (), park () method, the thread is blocked waiting to enter the state.
  • Synchronous blocking (BLOCKED) : get synchronized thread synchronization lock failure (because another thread synchronization lock is occupied).
  • Other blocking (TiMED_WAITHIN ): issued I / O request, the thread will enter the state by blocking the calling thread sleep () or join (). When sleep () timeout, the Join () wait for a thread to terminate or a timeout, or I / O processing is completed, the thread back to the operating state.

Death state (TERMINATED): When a thread to complete the task of running the state or other termination condition occurs, the thread switches to the termination of the state.

It is worth noting that the above state for the JVM thread state, the operating system does not react thread state.

                                            Thread state transition diagram

Thread priority

Each Java thread has a priority, which helps determine the operating system thread scheduling order. Thread priority is a positive integer, all the threads created default priority is 5 (Thread.NORM_PRIORITY), set the maximum priority of 10 (Thread.MAX_PRIORITY), the minimum priority 1 (Thread.MIN_PRIORITY). In all been waiting for processor resources and other resources thread, high priority thread will theoretically be more likely to be a priority scheduling.

Daemon thread

Daemon thread means unimportant thread (knight for a princess, it is the guardian, is optional spare tire), so that the process only when a daemon thread in the implementation of the process will immediately end of the run.    

Create a class that can be run

Thread class inheritance

1. Create a new class inheritance Thread class.

2. override run () method. The method body run () method represents the thread needs to complete the task. 

3. Create an instance of a subclass of Thread.

4. Call the thread object's start () method to start the thread.

public class myThread {
    public static void main(String[] args){
        Thread t = new newThread();
        t.start();
    }
}

class newThread extends Thread{
    @Override
    public void run() {
        System.out.println(this.getName()+":start!");
    }
}

Implement Runnable

1. Create a new class implements Runnable interface.

2. Rewrite the run method. The method body run () method represents the thread needs to complete the task.

3. Create a new instance of target class.

4. Thread instances created to target as a parameter.

5. Call the thread object's start () method to start the thread.

public class myThread {
    public static void main(String[] args){
        newThread nt = new newThread();
        Thread t = new Thread(nt);
        t.start();
    }
}

class newThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":start!");
    }
}

Advantages of both methods

1. Thread inherited this method easy to use, easier access to the current thread object.

2. implement Runnable this approach can inherit other parent; multiple threads can share a target object for multiple threads to handle the same situation with a resource.

You can directly call the run () method to open a thread

In fact, only calling thread object start () method to run the run the code in the method body () in the new thread, and direct calls run () method means that calling run () method in the current thread, that run () the method is as common method to deal with, and does not create a new thread .

public class myThread {
    public static void main(String[] args){
        newThread nt = new newThread();
        Thread t = new Thread(nt,"myThread");
        t.run();
    }
}

class newThread implements Runnable{
    @Override
    public void run() {
        System.out.println("Name:"+Thread.currentThread().getName());
    }
}
//结果
Name:main

Common API

Constructor

Thread (), Thread (String name ) // can pass a string or nothing passed, is to create a what tasks do not thread

Thread(Runnable target)

Thread (Runnable target, String name) // objects can be passed in a run, name as the name of the thread

Get Thread Information

static Thread currentThread () // Get the current thread object

long getID () // get thread identification

String getName () // get the thread name

int getPriority () // get the thread priority

Thread.state getState () // get the thread state

public class myThread {
    public static void main(String[] args){
        newThread nt = new newThread();
        Thread t = new Thread(nt,"myThread");
        t.start();
        newThread.getInformation(Thread.currentThread());
        newThread.getInformation(t);
    }
}

class newThread implements Runnable{
    @Override
    public void run() {
    }

    static void getInformation(Thread t){
        System.out.println("name:"+t.getName());
        System.out.println("id:"+t.getId());
        System.out.println("priority:"+t.getPriority());
        System.out.println("state:"+t.getState());
    }
}

//结果
name:main
id:1
priority:5
state:RUNNABLE
name:myThread
id:13
priority:5
state:TERMINATED

Set thread information

void setName () // Set the thread name

void setPriority () // Set the thread priority

void setDaemon (Boolean on) // set a daemon thread, only when the thread calls before the start () method before calling

Thread state judge

boolean isAlive () // determine whether the thread death,

boolean isDaemon () // determine thread is a daemon thread

boolean isInterrupted () // determine whether the thread is interrupted, and to turn it into a non-interrupted state

public class myThread {
    public static void main(String[] args){
        newThread nt = new newThread();
        Thread t = new Thread(nt,"myThread");
        System.out.println("未调用start()时:"+t.isAlive());
        t.setDaemon(true);
        t.start();
        newThread.getInformation(t);
        newThread.getInformation(Thread.currentThread());
    }
}

class newThread implements Runnable{
    @Override
    public void run() {
    }

    static void getInformation(Thread t){
        System.out.println(t.getName()+"-isAlive:"+t.isAlive());
        System.out.println(t.getName()+"-isDaemon:"+t.isDaemon());
        System.out.println(t.getName()+"-isInterrupted:"+t.isInterrupted());

    }
}

//结果
未调用start()时:false
myThread-isAlive:true
myThread-isDaemon:true
myThread-isInterrupted:false
main-isAlive:true
main-isDaemon:false
main-isInterrupted:false

sleep () method

This approach allows the current thread suspended for some time.

static void sleep (long millis) // Pause millis milliseconds

static void sleep (long millis, long nanos) // Pause millis milliseconds + nanos nanoseconds

join () method

join means to join, you can abstract that it is to join the ranks of the current thread, that is, the occurrence of t.join () the current thread caller t join the team when called, the current thread to wait t thread is finished before you begin .

public class myThread {
    public static void main(String[] args)throws InterruptedException {
        newThread nt = new newThread();
        Thread t = new Thread(nt,"subThread");
        t.start();
        t.join();
        for (int i = 1; i <= 1000; i++) {
            if (i%500==0) {
                System.out.println("mainThread finish!");
            }
        }

    }
}

class newThread implements Runnable{
    @Override
    public void run(){
        for (int i = 1; i <= 1000; i++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (i%500==0)
                System.out.println("subThread finish!");
        }
    }
}

The results are as follows, the main thread is clearly shorter than the sub-thread execution time, but still the main thread executing the final

subThread finish!
subThread finish!
mainThread finish!
mainThread finish!

There are two forms of method overloading

void join (long millis) // wait millis milliseconds

void join (long millis, long nanos) // wait millis milliseconds + nanos nanoseconds

join () internal use wait () method and notifyall () method to achieve, so it differs from sleep () method is, sleep method does not release the locks held, while the join () method will release the locks held .

// After t.join () instead t.join (50,50), different results: 
mainThread Finish! 
MainThread Finish ! 
Subthread Finish ! 
Subthread Finish !

yield () method

Let the current thread cup of the right to use, this time in the high-priority thread ready queue to be executed, in addition to the method does not release thread holds the lock.

Guess you like

Origin www.cnblogs.com/lht-record/p/11316088.html