Details of common threading methods in Java

join method: The thread executing the method enters the blocking state until the thread calling the method ends and then changes from blocking to ready state. The following:

​
import java.util.Date;
import java.text.SimpleDateFormat;

public class Test {

	public static void main(String[] args) {
		TimeThread thread = new TimeThread();
		thread.start();//It can also be written as: new TimeThread().start();
		CountThread countThread = new CountThread(thread);
		countThread.start();
	}
}//Main Method

class TimeThread extends Thread {//Time-like threads
	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			System.out.println("Practice 2##" + new Date());
			try {
				sleep(10000000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class CountThread extends Thread {//Class counting threads
	TimeThread timeThread;

	CountThread(TimeThread timeThread) {//Parametric construction method
		this.timeThread = timeThread;//Calling global variables
	}

	@Override
	public void run() {//override method
		for (int i = 0; i < 50; i++) {
			System.out.println("Technology 1¥¥¥" + i);
			if (i == 2) {
				try {
					timeThread.join();// The thread that executes the join method is blocked until the thread that calls the join method has finished executing // Here you can call it again without creating a global variable, directly: new TimeThread().start();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

​

Explain the join () method above: When the loop executes to i 2, the line of code executes, and the thread created by CounterThread enters the blocking state, until the thread corresponding to the timeThread variable ends, the thread created by CounterThread enters the ready state again, and then enters the execution state.

Note: 1. The thread object must call the start method before calling the join method, otherwise the thread will never enter the execution state.

interrupt method: Ends the blocking state of the thread in calling wait method of Object class or join method and sleep method of that class, and generates InterruptedException exception at calling wait, join and sleep method.

import java.util.Date;
import java.text.SimpleDateFormat;

public class Test {

	public static void main(String[] args) {
		TimeThread thread1 = new TimeThread();
		thread1.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread1.interrupt();//Call methods to block them
	}
}

class TimeThread extends Thread {
	@Override
	public void run() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:sss");
		String beforeTime = sdf.format(new Date());
		System.out.println("beforeTime: " + beforeTime);
		try {
			sleep(300000);
		} catch (InterruptedException e) {
			System.out.println("Program catches exceptions!");
		}
		String afterTime = sdf.format(new Date());
		System.out.println("afterTime: " + afterTime);
	}
}

Explanation above: In theory, beforeTime and afterTime should be 30 seconds apart, but because the thread class object executes the interrupt method after 1 second, the thread object terminates the blocking state ahead of time, resulting in the difference between beforeTime and afterTime less than 30 seconds.

* CurrtThread method: Returns the thread object currently executing.

import java.util.Date;
import java.text.SimpleDateFormat;

public class Test {

	public static void main(String[] args) {
		TimeThread thread1 = new TimeThread();
		thread1.start();
		CountThread countThread = new CountThread(thread1);
		System.err.println(countThread);
		countThread.start();
	}
}

class TimeThread extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			System.out.println("Practice 2##" + new Date());
			try {
				sleep(100000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class CountThread extends Thread {
	TimeThread timeThread;

	CountThread(TimeThread timeThread) {
		this.timeThread = timeThread;
	}

	@Override
	public void run() {
		Thread thread=Thread.currentThread();
		System.out.println(thread);
		for (int i = 0; i < 50; i++) {
			System.out.println("Technology 1¥¥¥" + i);
//			if (i == 2) {
//				try {
//					timeThread.join(); // thread blocking to execute join method until the thread calling join method has finished executing
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//			}
		}
	}
}

If the output object is getName(), the result is the same. Here are four procedures:

​
​
import java.util.Date;
import java.text.SimpleDateFormat;

public class Test {

	public static void main(String[] args) {
		Thread thread = new Thread();//These two lines are also possible: Thread thread = thread. current Thread ();
		Thread thread2 = thread.currentThread();// This is equivalent to:
    /**public class Test {

	public static void main(String[] args) {
		Thread thread = new TimeThread();
		System.out.println(thread);
		thread.start();
	}
}

class TimeThread extends Thread{

	@Override
	public void run() {
		Thread thread = Thread.currentThread();
		System.out.println(thread);
	}
}*/
		System.out.println(thread2);
		TimeThread thread1 = new TimeThread();
		System.out.println(thread1);// The method is used here.
		thread1.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread1.interrupt();
	}
}

class TimeThread extends Thread {
	@Override
	public void run() {
		TimeThread thread = (TimeThread) TimeThread.currentThread();
        //Equivalent: Thread thread = timeThread. current Thread ();
		System.out.println(thread);// The method is used here.
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:sss");
		String beforeTime = sdf.format(new Date());
		System.out.println("beforeTime: " + beforeTime);
		try {
			sleep(300000);
		} catch (InterruptedException e) {
			System.out.println("Program catches exceptions!");
		}
		String afterTime = sdf.format(new Date());
		System.out.println("afterTime: " + afterTime);
	}
}

class CountThread extends Thread {
	TimeThread timeThread;

	CountThread(TimeThread timeThread) {
		this.timeThread = timeThread;
	}

	@Override
	public void run() {
		Thread thread = Thread.currentThread();
		System.out.println(thread);
		for (int i = 0; i < 50; i++) {
			System.out.println("Technology 1¥¥¥" + i);
		}
	}
}

​

​
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {

	public static void main(String[] args) {
		new TimeThread().start();
	}
}
class TimeThread extends Thread{

	public TimeThread(){
		super("Time Thread");
	}
	@Override
	public void run() {
		printTime();
	}
	
	public void printTime(){
		Thread thread = Thread.currentThread();
		String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
		System.out.println(thread.getName()+",Current time:"+time);
		System.out.println(thread.getName()+",Current time:"+time);

	}
}
//Result:
//Time threads, current time: 15:12:51
//Time threads, current time: 15:12:51


public class Test {

	public static void main(String[] args) {
		TimeThread timeThread = new TimeThread();
		System.out.println("########"+timeThread);
		timeThread.start();
		
		timeThread.run();
	}
}

class TimeThread extends Thread{

	@Override
	public void run() {
		Thread thread = Thread.currentThread();
		System.out.println("@@@@@@@@"+thread);
	}
}
//Result:
########Thread[Thread-0,5,main]
@@@@@@@@Thread[main,5,main]
@@@@@@@@Thread[Thread-0,5,main]

Calling method isAlive(): Determines whether the thread is ready, running, or blocked, returns true if it is, or false if it is.

Note: Thread A executes the jion method called by "dead" thread B, and thread A does not block.

​
import wo.T;

public class Test {

	public static void main(String[] args) {
		//Is Is Alive Surviving
		Thread thread=Thread.currentThread();
		TimeThread timeThread = new TimeThread(thread);
		System.out.println("########"+thread.isAlive());
		timeThread.start();
	}
}

class TimeThread extends Thread{
	Thread thread;
	public TimeThread(Thread thread) {
			 this.thread=thread;
		 }
	
	@Override
	public void run() {
		try {
			sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("$$$$$$$"+thread.isAlive());
	}
}
//Result: // Because the time thread is blocked
########true
$$$$$$$false


​For example 1

 

public class Test {

	public static void main(String[] args) {
		Thread thread = Thread.currentThread();
		new PrintThread(thread).start();
		System.out.println("main Thread state:"+thread.isAlive());
	}
}

class PrintThread extends Thread{

	private Thread thread;
	
	public PrintThread(Thread thread){
		this.thread = thread;
	}
	
	@Override
	public void run() {
		try {
			sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.err.println("main Thread state:"+thread.isAlive());
	}
}
//For example 2:
public class Test{
	
	String currentTime;
	
	public static void main(String[] args) {
		Test watch = new Test();
		TimeThread timeThread = watch.new TimeThread ();
		timeThread.start();
		watch.new DisplayThread(timeThread).start();
	}

	class DisplayThread extends Thread{

		TimeThread timeThread;
		public DisplayThread(TimeThread timeThread) {
			this.timeThread = timeThread;
		}
		
		@Override
		public void run() {
			System.out.println("Time Thread Status:"+timeThread.isAlive());
			try {
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Time Thread Status:"+timeThread.isAlive());//Display threads blocked for 500 milliseconds, and time threads "die"
			try {
				timeThread.join();//Display threads execute jion methods called by "dead" time threads, and display threads do not block
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(currentTime);
		}
	}

	class TimeThread extends Thread{
		@Override
		public void run() {
			currentTime = new java.util.Date().toString();
		}
	}
}
//Result:
//Time Thread Status:true
//Time Thread State: false
Thu Aug 29 15:52:42 CST 2019
//For example three

The following is not very clear why this result: only an additional time thread run():

import wo.T;

public class Test {

	public static void main(String[] args) {
		//Is Is Alive Surviving
		Thread thread=Thread.currentThread();
		TimeThread timeThread = new TimeThread(thread);
		System.out.println("########"+thread.isAlive());
		timeThread.start();
		timeThread.run();
	}
}

class TimeThread extends Thread{
	Thread thread;
	public TimeThread(Thread thread) {
			 this.thread=thread;
		 }
	
	@Override
	public void run() {
		try {
			sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("$$$$$$$"+thread.isAlive());
	}
}
//Result:
########true
$$$$$$$true
$$$$$$$true

Call the daemon method setDaemon():

setDaemon method: Used to set a thread that has not yet invoked the thread start method to a daemon thread. Daemon threads are mainly used to provide services for the operation of other threads (the garbage collection mechanism in Java is daemon threads), which belong to the thread that created it.

Note: The daemon thread terminates with the termination of the last non-daemon thread, as follows:

public class Test {

	public static void main(String[] args) {
		TimeThread timeThread = new TimeThread();
		timeThread.setDaemon(true);
		timeThread.start();/**The thread object calls setDaemon before it calls start and the value is set to true. The thread is a daemon thread, which ends with the end of the last non-daemon thread in the process.*/
		try {
			timeThread.sleep(12);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class TimeThread extends Thread{

	@Override
	public void run() {
		while(true) {
		System.out.println(111);
		}
	}
}
//The result is that the non-daemon threads are sleeping in these 12 seconds, while the natural daemon threads continue to run until they end together.

Note: Other non-daemon threads initiated in the process do not end with the end of a non-daemon thread.

Other methods:

void start(): To start the thread, the Java virtual machine is responsible for calling the thread's run() method. It is illegal to start a thread multiple times.

void sleep(long millis): Thread class static method in which threads are blocked and in a Runnable state after a specified time (in milliseconds) arrives, rather than immediately in an execution state.

void yield(): Static method, where the current thread abandons the CPU resources and returns to the ready state so that other threads with priority no less than this thread have the opportunity to be executed.

Void setPriority (int new Priority): Set the priority of the current thread. The higher the priority of the thread, the more times the thread gets executed. The priority of the Java thread is expressed in integers, ranging from 1 to 10. The Thread class has three static constants:

1. Statiint MAX_PRIORITY with the highest priority value of 10;

2.static int NORM_PRIORITY default priority value is 5;

3.static int MIN_PRIORITY The lowest priority value is 1;

Note: For multiple threads created by the same thread class, the higher the priority of the thread, the more likely the thread will get the execution times; but for threads created by different thread classes, the higher the priority of the thread, the more execution times will not necessarily be. The code complexity of this run method is related.

int getPriority(): Gets the priority of the current thread.

import java.util.Date;

public class Test {

	public static void main(String[] args) {
		CounterThread countThread = new CounterThread("Thread 1");
		countThread.start();
		TimeThread timeThread = new TimeThread("Thread 2%%%%%%%%%%%%%%%%%");
		timeThread.setPriority(6);
		timeThread.start();
	}
}

class TimeThread extends Thread{

	@Override
	public void run() {
		while(true) {
		System.out.println(getName()+new Date());
		}//At this time, although the priority of time threads is high, but the code is more complex, not necessarily get more execution times.
	}
	TimeThread(String name){
		super(name);
	}
}

class CounterThread extends Thread{

	@Override
	public void run() {
		while(true) {
		System.out.println(getName()+1111);
		}
	}
	CounterThread(String name){
		super(name);
	}
}//So when we use this method, we still want to see if the same class is created, if not, setting priority does not have much effect.

 

 

Tags: Java less

Posted on Thu, 29 Aug 2019 02:30:13 -0700 by rledieu