A:
Because some readers feedback my multi-threaded column should start from the foundation, so this article will make up the multi-threaded related basic knowledge, as Java concurrency and multi-threading column first article, mainly introduces some basic knowledge of Java multi-threading
Two: Java thread status
public enum State {
/** * Thread state for a thread which has not yet started. */
NEW,
/** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,
/** * Thread state for a terminated thread. * The thread has completed execution. */
TERMINATED;
}
Copy the code
Java threads have six states
1.NEW: The newborn state, in which the thread was created but did not call the start() method
2.RUNNABLE: the RUNNABLE thread calls the start() method to enter this state, which can be scheduled by the CPU
3.BLOCKED: A thread is BLOCKED by a synchronized lock
Wait (), join(), locksupport.park () will enter this state
Wait (timeout), sleep(timeout), join(timeout), locksupport. parkNanos(timeout), Methods such as locksupport.parkuntil () enter this state
The state is TERMINATED by calling the stop(), destroy() and other methods (removed in Java8 because they are unsafe) or by threading the run() method.
Three: thread creation
Implement Runnable implement the run() method
public class TestThread implements Runnable {
@Override
public void run(a) {
System.out.println("Java multithreading");
}
public static void main(String[] args) {
Thread thread = new Thread(newTestThread()); thread.start(); }}Copy the code
2. Override the run() method by inheriting Thread
public class TestThread extends Thread {
@Override
public void run(a) {
System.out.println("Java multithreading");
}
public static void main(String[] args) {
TestThread thread = newTestThread(); thread.start(); }}Copy the code
3. Implement Callable, implement call() method
public class TestThread implements Callable {
@Override
public Object call(a) throws Exception {
System.out.println("Java multithreading");
return null;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask<>(new TestThread());
futureTask.run();
// Block to get the result of the thread's executionObject o = futureTask.get(); }}Copy the code
Four: thread stop and interrupt
Stop of thread
There are two ways to stop a thread
Method 1: forcibly stop a thread by calling stop(), destroy() and other methods. This method has serious security problems and is not recommended and has been removed from java8.
Method 2: The run() method completes execution
public class TestThread implements Runnable {
// Stop the thread with a volatile variable
private static volatile boolean flag = false;
@Override
public void run(a){
while(! flag){ System.out.println("Java multithreading"); }}public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new TestThread());
t.start();
Thread.sleep(50);
flag = true; }}Copy the code
Thread interruption
InterruptedException is thrown if a thread in a Java virtual machine is interrupted or WAITING or TIMED_WAITING is interrupted. Java provides some apis for interrupts. Interrupt () interrupts a thread, and isInterrupted() lets you know if a thread has been interrupted. The interrupt flag can also be used to stop a thread.
public class TestThread implements Runnable {
@Override
public void run(a){
// Threads can be stopped by modifying interrupt flags
while(! Thread.currentThread().isInterrupted()){ System.out.println("Java multithreading"); }}public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new TestThread());
t.start();
Thread.sleep(500);
// Change the interrupt flag to truet.interrupt(); }}Copy the code
The results are as follows:
InterruptedException is thrown when a thread in WAITING or TIMED_WAITING is interrupted
The results are as follows:
If you call interrupt(), the thread does not stop because InterruptedException resets the interrupt to false. This is because while in WAITING or TIMED_WAITING, The interrupt should then be left to the interrupted thread to decide whether to interrupt.
If we do not need to interrupt, we can call interrupt() again while handling an exception.
The code is as follows:
public class TestThread implements Runnable {
private static volatile boolean flag = false;
@Override
public void run(a){
while(! Thread.currentThread().isInterrupted()){try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//TODO Before the interrupt we can also do some operations such as closing the resource to save data etc
Make sure to interrupt the thread by calling the interrupt() method
Thread.currentThread().interrupt();
e.printStackTrace();
}
System.out.println("Java multithreading"); }}public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new TestThread());
t.start();
Thread.sleep(500);
t.interrupt();
}
Copy the code
The results are as follows:
You can see that the thread has stopped.
Five conclusion
Java Multithreading column will introduce some concurrent tools commonly used in java.ununit.current package and source code analysis. This article as the first article of Java multithreading column, mainly introduces some basic knowledge of Java threads. If you are interested in Java multithreading knowledge, you can collect Java multithreading column.