java multithreading principle learning notes

Posted by ckdoublenecks on Thu, 17 Feb 2022 05:01:07 +0100

1, Preliminary understanding of java thread

1. java create thread

Several ways of creating threads in java

  1. Inherit Thread class
  2. Implement Runnable interface
  3. Create a thread pool using ExecutorService
  4. Implement the Callable interface to create a thread with a return value

Example:

//Inherit Thread class
public class MyThread extends Thread { 
	@Override
	public void run() {
	}
 }


//Implement Runnable interface
public class MyThread1 extends ClassA implements Runnable {
	@Override
	public void run() {
	}
}

//Create a thread pool using ExecutorService
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
	pool.execute(new Runnable() {
		@Override
		public void run() {
			System.out.println("thread "+Thread.currentThread().getName()+"Start!");
		}
	});
}
pool.shutdown();

// Implement the Callable interface to create a thread with a return value
public class CallableDemo implements Callable<String> { 
	public static void main(String[] args) throws ExecutionException, InterruptedException { 
		ExecutorService executorService= Executors.newFixedThreadPool(1);
		CallableDemo callableDemo=new CallableDemo();
		Future<String> future=executorService.submit(callableDemo); 
		System.out.println(future.get()); 			
		executorService.shutdown();
	 } 
	 @Override 
	 public String call() throws Exception { 
    	int a=1; 
	 	int b=2;
	 	System.out.println(a+b); 
	 	return "results of enforcement:"+(a+b);
	 } 
}

2. Thread life cycle

The whole life cycle of a thread includes six states (NEW, RUNNABLR, BLOCKED, WAITING, TIME_WAITING, TERMINATED).

NEW: in the initial state, the thread is built, but the start method has not been called yet

RUNNABLED: running state. JAVA threads call the ready and running states of the operating system "running".

BLOCKED: BLOCKED state, which means that the thread enters the waiting state, that is, the thread gives up the CPU usage right for some reason. For example, wait for the lock, or wait for the I/O to complete

WAITING: WAITING state, the state after executing the wait() or join() method. Wake up by executing the notify() or notifyAll() methods

TIME_WAITING: timeout waiting state. It will return automatically after timeout. sleep(), wait(), join() and other methods are executed and the state after timeout is set

TERMINATED: the TERMINATED status indicates that the current thread has completed execution.


The sleep method will not release the lock, and will continue to execute when the set timeout expires. The wait method will release the lock. After being awakened by the notify method, it will compete for the lock and then execute.

3. Start and stop of java thread

Thread start:
The java thread starts by calling the start() method instead of the run() method.

Thread termination:
The java thread terminates the thread through the interrupt() method instead of the stop() method. The stop method will not ensure the normal release of thread resources when ending a thread, so it may lead to some uncertain states in the program. The interrupt() method tells the thread that it can interrupt by setting the flag bit in the thread. The specific interrupt operation is completed by the thread itself

       Thread thread=new Thread(()->{
            while(!Thread.currentThread().isInterrupted()){//The default is false 
                i++;
            }
            System.out.println("i:"+i);
        });
        thread.start();

        TimeUnit.SECONDS.sleep(1);
        thread.interrupt(); //Set isInterrupted to true

Thread reset:
java can use thread In interrupted mode, reset the interrupt flag bit of the thread.

        Thread thread=new Thread(()->{
            while(true){
                if(Thread.currentThread().isInterrupted()){//The default is false 
                    System.out.println("before:"+Thread.currentThread().isInterrupted());
                    Thread.interrupted(); //Reset - return to initial state
                    System.out.println("after:"+Thread.currentThread().isInterrupted());
                }
            }
        });
        thread.start();

        TimeUnit.SECONDS.sleep(1);
        thread.interrupt(); //Set isInterrupted to true

If an InterruptedException exception is thrown during the running process of a java thread, the interrupt identification bit will also be reset, and then an exception will be thrown

Topics: Java