Java foundation -- Day22 -- multithreading, lock, thread pool

Day 21 notes (Part 2)

1, Threads and processes (understand)

1.1 process

  • The code we write and the references we download are just a pile of files when they are not running
  • After these codes and references are run, they can become running programs and processes
  • A reference program has at least one process

1.2 threads

  • A process may accomplish multiple tasks at the same time
  • For example: Netease cloud
    • Lyrics can be displayed
    • Can play video
    • Can play music
    • You can scroll the progress bar
    • You can view comments
  • The above operations seem to be possible at the same time
  • In fact, there are many threads performing different tasks
    • Some threads play videos
    • Some threads play audio
    • Some threads drive progress bar changes
    • . . .
  • These threads execute alternately under the quota scheduling of the CPU. We can't feel...

2, Thread

2.1 definitions

  • A thread is an execution thread in a program. The Java virtual machine allows applications to run multiple execution threads concurrently.
  • Each thread has a priority, and the execution of high priority threads takes precedence over low priority threads.

2.2 method of creating objects (Master)

  • Inherit Thread class
  • Create the object of this subclass
  • Call the start method
  • =========================
  • Implement Runnable interface
  • Create an object that implements the class and put it into the Thread constructor as a parameter
  • Start the thread with start

3, Inherit Thread class (Master)

  • Create a subclass of Thread
  • Create Thread subclass object
  • Call the start method
package com.qf.thread;

public class Demo01 {
	public static void main(String[] args) {
		// Create subclass objects
		MyThread t1 = new MyThread();
		MyThread t2 = new MyThread();
		
		// Start thread: start method called
		t1.start();
		t2.start();
		
		for (int i = 0; i < 100; i++) {
			System.out.println("main thread ==========:" + i);
		}
		
		System.out.println("main End of thread running...");
	}
}
/**
 * Inherit the Thread class and override the run method
 * @author Dushine2008
 *
 */
class MyThread extends Thread{
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println("Child thread" + Thread.currentThread().getId() + ":"+i);
		}
	}
}

4, Implement Runnable interface (Master)

  • Write an implementation class to implement the Runnable interface
  • Override run method
  • Create an object of the Runnable implementation class
  • Create a Thread object and pass in an instance of the parameter Runnable in the construction method
  • Call the start method to start the thread
package com.qf.thread;

public class Demo02 {
	public static void main(String[] args) {
		// Create Runnable implementation class object
		MyRunnableThread r = new MyRunnableThread();
		// Create Thread object
		Thread t1 = new Thread(r,"Thread 01");
		Thread t2 = new Thread(r,"Thread 02");
		
		// Start thread
		t1.start();
		t2.start();
		
		// Output 0 -- 100 in the main thread
		for (int i = 0; i < 100; i++) {
			System.out.println("main thread :" + i);
		}
		
		System.out.println("main End of thread running...");
		
	}
}

/**
 * Write an implementation class to implement the Runnable interface
 * Override run method
 * @author Dushine2008
 *
 */
class MyRunnableThread implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println("Child thread" + Thread.currentThread().getName() + ":" + i);
		}
	}
	
}

5, Common thread methods (Master)

5.1 currentThread

  • Returns the current running thread object
  • Including thread name, priority, group and other information

5.2 getId

  • Returns the id of the current thread
  • id is the id allocated by the system and the unique id of the current thread

5.3 getName

  • Gets the name of the current thread
  • The name of the thread can be passed in through the constructor method or set through the setName method

5.4 setName

  • Sets the name of the specified thread

5.5 getPriority

  • Gets the priority of the current thread

5.6 setPriority

  • Set thread priority
  • The priority range is 1-10, and the default priority is 5
  • The higher the number, the higher the priority, and the higher the probability of execution
package com.qf.thread;

public class Demo03 {
	public static void main(String[] args) {
		/**
		 * 	currentThread() 
          		Returns a reference to the thread object currently executing.
          	long getId() 
			          Returns the identifier of the thread. 
			String getName() 
			          Returns the name of the thread. 
			int getPriority() 
			          Returns the priority of the thread. 
		 */
		
		MyRunnableThread02 r = new MyRunnableThread02();
		Thread t1 = new Thread(r, "Thread 01");
		Thread t2 = new Thread(r, "Thread 022222");
		
		t1.setName("1 Thread number.............");
		t1.setPriority(1);
		t2.setPriority(10);
		
		t1.start();
		t2.start();
		
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getId() + "===" + Thread.currentThread().getName() + "===" + i);
		}
		
		System.out.println(t1.getPriority() + "-------------------------------------------------");
		System.out.println(t2.getPriority() + "-------------------------------------------------");
		System.out.println(Thread.currentThread().getPriority() + "++++++++++++++++++++++++++++++++++++++++++++");
		
	}
}

class MyRunnableThread02 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread() + ":" + i);
		}
	}
	
}

5.7 join

  • Insertion – queue jumping – priority execution
  • The resources will not be released until the execution of the thread jumping in the queue is completed, and other threads can continue to rob resources
package com.qf.thread;

public class Demo04 {
	public static void main(String[] args) {
		/**
		 * 	boolean isDaemon() 
			          Test whether the thread is a daemon thread. 
         	void join() 
          		Wait for the thread to terminate. 
          	void setDaemon(boolean on) 
          		Mark the thread as a daemon or user thread. 
          	void setName(String name) 
          		Change the thread name to be the same as the parameter name. 
           	void setPriority(int newPriority) 
          		Change the priority of the thread. 
          	static void sleep(long millis) 
          		Hibernate (pause execution) the currently executing thread for a specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler. 
          	static void yield() 
          		Pause the currently executing thread object and execute other threads. 
		 */
		
		MyRunnableThread04 r = new MyRunnableThread04();
		Thread t1 = new Thread(r, "Sub thread 01");
		
		t1.start();
		
		// Main thread output 0 --- 100
		for (int i = 0; i < 100; i++) {
			if (i == 20) {
				try {
					// main is an ordinary user. If there is no recharge, let the ordinary user experience 20 times first, and then recharge the member first
					t1.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName() + "===" + i);
		}
	}
}

class MyRunnableThread04 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread() + ":" + i);
		}
	}
	
}

5.8 setDaemon

  • Set as daemon thread
  • Other threads become foreground threads
  • After the execution of other threads is completed, the daemon thread will automatically end, even if the execution is not completed
package com.qf.thread;

public class Demo05 {
	public static void main(String[] args) {
		MyRunnableThread05 r = new MyRunnableThread05();
		Thread t1 = new Thread(r, "Sub thread 01");
		Thread t2 = new Thread(r, "Sub thread 02");
		Thread t3 = new Thread(r, "Sub thread 03");
		Thread t4 = new Thread(r, "Daemon thread 04=================");
		
		t4.setDaemon(true);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		
		// Main thread output 0 --- 100
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName() + "===" + i);
		}
	}
}
class MyRunnableThread05 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread() + ":" + i);
		}
	}
}

5.9 yield

  • Comity thread
  • Let other threads execute first. Comity may not succeed
package com.qf.thread;

public class Demo06 {
	public static void main(String[] args) {
		MyRunnableThread06 r = new MyRunnableThread06();
		Thread t1 = new Thread(r, "Sub thread 01");
		
		t1.start();
		
		for (int i = 0; i < 100; i++) {
			if (i % 10 == 0) {
				// main is an ordinary user without recharging. You should be humble every 10 times
				Thread.yield();
			}
			System.out.println(Thread.currentThread().getName() + "===" + i);
		}
	}
}


class MyRunnableThread06 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread() + ":" + i);
		}
	}
}

5.10 sleep

  • Thread sleep
package com.qf.thread;

public class Demo07 {
	public static void main(String[] args) {
		System.out.println("Countdown start...");
		
		for (int i = 10; i >= 0; i--) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Rocket launch countdown:" + i);
		}
		System.out.println("Launched...");
	}
}

Tags: Java

Posted by nawhaley2265 on Sat, 21 May 2022 06:52:44 +0300