Thread 和 Runnable

Thread 和 Runnable

1 Introduction

Java mainly by java.lang.Threadclass and java.lang.Runnableimplement threading mechanism interface.

  1. Thread Classes for the underlying operating system thread architecture provides a unified interface
  2. RunnableInterface for the association Threadto provide the code execution thread object

2. Create Thread and Runnable objects

2.1 Create a Runnable object

There are two ways to create a Runnable:

Create an anonymous class implements Runnable interface
Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello from thread");
    }
};
Or use a lambda expression
Runnable r = () -> System.out.println("Hello from thread");

2.2 Creating a Thread object

Created in two ways:

Runnable object as a parameter to the Thread class constructor
Thread t = new Thread(r);
Thread class inheritance override its turn run()Method
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Hello from thread");
    }
}
// ...
MyThread mt = new MyThread();

3. get and set the thread state

Several methods:

  • getName() : Get the thread name

  • setName(): Set the thread name

  • isAlive(): Judge thread survival status, survival returns true, do not survive to return false (only the implementation of start()the method, the thread was started)

  • getState(): Get the thread execution state

    Execution state of the thread by Thread.State enumeration constants identify:

    • NEW: the thread has not started
    • RUNNABLE: JVM thread is executed
    • BLOCKED: thread is blocked waiting for a monitor lock
    • WAITING: thread wait indefinitely for another thread to perform a particular operating
    • TIMED_WAITING: a thread waits for another thread to perform certain operations in a specific local time
    • TERMINATED: thread has quit
  • setPriority(): Sets the thread priority

    Transmitted to the priority value between Thread.MIN_PRIORITYand Thread.MAX_PRIORITYbetween, and Thread.NORMAL_PRIORITYit is determined that the default priority

  • isDaemon(): To determine whether the thread is a daemon. Daemon returns true, not false returns

  • start(): Thread starts associated with the object.

    If you have already started and running before the thread, or the thread dies, this method will throw java.lang.IllegalThreadStateException


4. More advanced operation threaded tasks

Interrupt thread

When a thread is interrupted, it will throw java.lang.InterruptedExceptionthis mechanism consists of the following three ways:

  • void interrupt(): Thread associated interrupt this method is called Thread object. The thread's interrupt status is cleared
  • static boolean interrupted(): Verify whether the current thread has been interrupted. The thread's interrupt status will be cleared by this method
  • boolean isInterrupted(): Verify whether the thread has been interrupted. The thread's interrupt status is not affected by this method
Waiting thread

Thread class provides three join()methods to allow the calling thread to wait for a thread of execution thread object associated with this method is finished.

  • void join(): Wait indefinitely until the thread dies
  • void join(long millis): Wait up millis milliseconds before the thread dies
  • void join(long millis, int nanos): Wait up millis milliseconds plus nanos nanoseconds before the thread death
Thread sleep

Thread class declares a static method causes the thread to sleep (temporarily cease execution)

  • void sleep(long millis): Sleep millis milliseconds
  • void sleep(long millis, int nanos): Sleep millis milliseconds and nanos nanoseconds

5. Thread and Runnable difference (significant)

First, talk about ideas to achieve multi-threaded, there are two main ways:

  1. Through inheritance Thread class, override run()method
class MyThread extends Thread{
    private int ticket = 5;
    @Override
    public void run(){
        for (int i=0;i<10;i++)
        {
            if(ticket > 0){
                System.out.println("ticket = " + ticket--);
            }
        }
    }
}

class ThreadDemo{
    public static void main(String[] args){
        new MyThread().start();
        new MyThread().start();
        new MyThread().start();
    }
}
  1. By implementing the Runnableinterface, multithreading
class MyThread implements Runnable{
    private int ticket = 5;
    @Override
    public void run(){
        for (int i=0;i<10;i++)
        {
            if(ticket > 0){
                System.out.println("ticket = " + ticket--);
            }
        }
    }
}

class RunnableDemo{
    public static void main(String[] args){
        MyThread my = new MyThread();
        new Thread(my).start();
        new Thread(my).start();
        new Thread(my).start();
    }
}

These two methods are the same, only the implementation of the start()order, will start a thread of execution.

Which generated inheritance Thread Thread each is independent , to achieve Runnable thread generation is a shared resource , which is our top of the examples, the results of the final output is not the same:

  • The first way each thread independently performed for cycle operation (resources are not shared), so the final result will take turns print results returned three times 54321.
ticket = 5
ticket = 4
ticket = 3
ticket = 2
ticket = 1
ticket = 5
ticket = 4
ticket = 3
ticket = 2
ticket = 1
ticket = 5
ticket = 4
ticket = 3
ticket = 2
  • The second way, because 3 Thread objects together to execute code in a Runnable object, so to achieve resource sharing, print out the final results only once 54321, but this approach is likely to cause insecurity thread .
ticket = 5
ticket = 4
ticket = 3
ticket = 2
ticket = 1
to sum up:
  1. Thread class method inherited generated each thread is independent, resources can not be shared
  2. Implement Runnable generated Since the common thread Runnable method, resource sharing can be achieved between each other, but it is thread safe, it is necessary to perform locking operations
  3. Only perform start()operations, the thread will be created to perform
  4. General development process, we are accustomed to use Runnable interface to create a class that implements a thread, because you can share resources, more in line with business needs

Guess you like

Origin www.cnblogs.com/weixuqin/p/11419970.html