Three ways to create Java threads

Inheriting Thread objects

class ThreadImpOne extends Thread{
        @Override
        public void run(){
            System.out.println("ThreadImpOne"); }}Copy the code

Implement the Runnalbe interface

class ThreadImpTwo implements Runnable{
    @Override
    public void run() {
        System.out.println("ThreadImpTwo"); }}Copy the code

Note: light theory is not enough, here to send you a set of 2020 latest Java architecture practice tutorial + factory interview treasure, click here to get together to exchange progress oh!

Implement Callable interface import Java. Util. Concurrent. Callable; import java.util.concurrent.FutureTask; public class Main{ public static void main(String args[]) throws Exception{ ThreadImpThree threadThree = new ThreadImpThree(); FutureTask<Integer> task = new FutureTask<Integer>(threadThree); new Thread(task).start(); System.out.println(task.get()); } } class ThreadImpThree implements Callable<Integer>{ @Override public Integercall(){
        System.out.println("ThreadThreeImp");
        return 666;
    }
}
//ThreadThreeImp
//666Copy the code

Java threads have five states

New state: After the thread object is created, it enters the New state. Thread Thread = new Thread().

Runnable: An executable state, waiting for CPU scheduling. The new state calls thread.start() to enter the ready state

Running: The thread takes CPU time to execute

Blocked: THE CPU usage is given up and temporarily stopped due to some reason. There are three main reasons for giving up

Wait blocking: The wait method of the synchronized object was called

Synchronized blocked: The thread failed to obtain the Synchnoized synchronization lock and entered the synchronization blocked state

Other blocking: the thread’s sleep or JOIN methods are called, or an IO request is made. When the sleep state times out, the join waiting thread finishes, or the I/O is ready, the thread goes to the ready state

Dead: The thread enters the Dead state when it finishes executing or exits abnormally.

There are three ways to terminate a Java thread

Modify flag bit

For example, while(true) {… } similar loop structure to continuously receive requests from the client. You can end the run() method by modifying the flag bit

while(!exit) {doSomething();
}Copy the code

The stop method terminates the thread

The thread.stop() method can terminate a thread immediately, but the stop() method is not safe

Calling stop() immediately stops all remaining work in the run() method, including ina catch or finally statement, and throws a ThreadDeath exception (which normally does not require a display catch), so some clear work may not be done. Closure of files, databases, etc.

Thread.interrupt, as opposed to stop, sets the thread's interrupt flag to true. If the thread wants to respond to the interrupt, it interrupts; if not, it ignores the message. The interrupt of the thread depends on the thread itself. public class Main{ public static void main(String args[]) throws Exception{ Thread thread = new Thread(new ThreadImp());  thread.start(); Thread.sleep(3000); thread.interrupt(); } } class ThreadImp extends Thread{ @Override public voidrun() {
        while(true) {
            System.out.println(Thread.interrupted());
            for(int i = 0; i < 100000; i++) {
                for(int j = 0; j < 50000; j++) {long value = Integer.MAX_VALUE * Integer.MAX_VALUE; }}}}} // The thread will always run, and there will definitely be an outputtrueCopy the code

The above thread will run all the time, and will only print true once, and false all the other times. To understand why, you can read more about thread interrupt mechanism, which is not described here.

Note: Theory alone is not enough. Here we have a new Java architecture tutorial for 2020 + Xuanwo008 with a small assistant VX: Xuanwo008.

Big factory monthly salary 30K +

How w to effectively win the offer of Ali, Tencent and other eight big factories? Collected the Core Knowledge points of Java sorted out by Meituan Daishen, which will be asked by the interviewer during the interview