Thread 和 Runnable
1 Introduction
Java mainly by java.lang.Thread
class and java.lang.Runnable
implement threading mechanism interface.
Thread
Classes for the underlying operating system thread architecture provides a unified interfaceRunnable
Interface for the associationThread
to 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 namesetName()
: Set the thread nameisAlive()
: Judge thread survival status, survival returns true, do not survive to return false (only the implementation ofstart()
the method, the thread was started)getState()
: Get the thread execution stateExecution 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 priorityTransmitted to the priority value between
Thread.MIN_PRIORITY
andThread.MAX_PRIORITY
between, andThread.NORMAL_PRIORITY
it is determined that the default priorityisDaemon()
: To determine whether the thread is a daemon. Daemon returns true, not false returnsstart()
: 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.InterruptedException
this mechanism consists of the following three ways:
void interrupt()
: Thread associated interrupt this method is called Thread object. The thread's interrupt status is clearedstatic boolean interrupted()
: Verify whether the current thread has been interrupted. The thread's interrupt status will be cleared by this methodboolean 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 diesvoid join(long millis)
: Wait up millis milliseconds before the thread diesvoid 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 millisecondsvoid 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:
- 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();
}
}
- By implementing the
Runnable
interface, 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:
- Thread class method inherited generated each thread is independent, resources can not be shared
- 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
- Only perform
start()
operations, the thread will be created to perform - 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