[learn Java notes from scratch] multithreading

Keywords: Java REST

You can pay attention to the author's account and the Java notebook from scratch. You can also go to the author's blog Garden to learn from the catalog. This film will be based on the black horse programmer job class video for learning and data sharing, and take notes and their own views. Welcome to study and discuss together.

[learn Java notes from scratch] directory

Difference between process and thread

Process: is a program in execution, that is, once the program is loaded into memory and ready to execute, it is a process. Process is the basic concept of resource allocation, the basic unit of scheduling operation, and the unit of concurrent execution in the system.
Thread: each task executed in a single process is a thread. A thread is the smallest unit in a process that performs an operation.
A process can have one or more threads

Advantages and disadvantages of single thread and multi thread

Single thread: high security but low efficiency
Multithreading: low security and high efficiency
Multithreading cases: 360, Xunlei, etc

Class Thread

Method one of creating thread

First, create a class, inherit the Thread class, and override the run method.

public class MyThread extends Thread{
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(getName()+i);
		}
	}
}

Call the MyThread class in the main function, and then use the start () method to call it.

public class ThreadDemo {
	public static void main(String[] args) {
		//Create a thread
		MyThread mt = new MyThread();
		mt.setName("Thread-1:");
		mt.start();
		
		//Create another thread
		MyThread mt2 = new MyThread();
		mt2.setName("Thread-2:");
		mt2.start();
 	}

}

The output (partial) is as follows

It can be seen that thread one and thread two alternate. This is because when the computer processes two threads running at the same time, it uses a very short time to switch between the two threads and make random calls. But the speed is too fast to detect.

Method 2 of creating thread

Another way to create a Thread is to declare a class that implements the Runnable interface. The class then implements the run method. You can then assign an instance of the class to pass and start as a parameter when you create a Thread.

public class MyThread2 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName() + i);
		}
	}
}
public class ThreadDemo2 {
	public static void main(String[] args) {
		MyThread2 mt = new MyThread2();
		Thread t = new Thread(mt);
		t.setName("Thread-1:");
		t.start();
		
		MyThread2 mt2 = new MyThread2();
		Thread t2 = new Thread(mt);
		t2.setName("Thread-2:");
		t2.start();
		
	}

}

The output (partial) is similar to the previous output

Ticket sales in simulated railway station

1. Create thread class first
Requirements: 100 tickets, continuous ticket sales, ticket number is 0, stop ticket sales.

public class ThreadTicket implements Runnable {

	private static int ticketNum = 100;

	@Override
	public void run() {
		while (true) {
			if (ticketNum > 0) {
				System.out.println(Thread.currentThread().getName() + ":" + ticketNum--);
			}
		}

	}

	public static int getTicketnum() {
		return ticketNum;
	}

}

Main function

public class ThreadTicketDemo {
	public static void main(String[] args) {
		ThreadTicket tt = new ThreadTicket();
		Thread t1 = new Thread(tt);
		t1.setName("Ticket outlet 1");
		t1.start();
		
	}

}

Output results (partial)

The railway station can't have only one ticket office, so add more threads

public class ThreadTicketDemo {
	public static void main(String[] args) {
		ThreadTicket tt = new ThreadTicket();
		Thread t1 = new Thread(tt);
		t1.setName("Ticket outlet 1");
		t1.start();
		
		Thread t2 = new Thread(tt);
		t2.setName("Ticket outlet 2");
		t2.start();
		
		Thread t3 = new Thread(tt);
		t3.setName("Ticket outlet 3");
		t3.start();
	}

}

Output results (partial)

Careful friends should find that the last ticket is very irregular. For example, when the last ticket is being sold by the ticket office 2, the eleventh ticket is still being sold by the ticket office 3. In fact, this is in line with the law of life. Let's think about our experience of buying tickets. Because every thread called by cpu is random, and the running of thread also needs time. When ticket office 3 sells the eleventh ticket, cpu calls ticket office 2 continuously to sell tickets continuously.

To make the program more obvious, we add sleep ()

public class ThreadTicket implements Runnable {

	private static int ticketNum = 100;

	@Override
	public void run() {
		while (true) {
			if (ticketNum > 0) {

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				System.out.println(Thread.currentThread().getName() + ":" + ticketNum--);
			}
		}

	}

	public static int getTicketnum() {
		return ticketNum;
	}

}

Re export

Firstly, it can be found that the program slows down obviously, and then some errors are found. The sixth ticket is sold twice, and one ticket is sold when there is no ticket. This is because when the number of tickets is normal, for example, one of the threads judges and enters the rest. Another process is coming to judgment. At this time, the two processes pass the judgment at the same time. After the rest, they output at the same time, and this error will appear.

So how to solve this problem?
synchronized: synchronization (lock) can modify code blocks and methods. Once the modified code blocks and methods are accessed by a thread, they will be locked directly, and other threads will not be able to access them.

Method 1:
Synchronization code block:

Synchronized (lock object){

}

Note: lock objects need to be shared by all threads
Method two:
Synchronization method: a method decorated with the keyword synchronized is used. Once it is accessed by one thread, the whole method will be locked and other threads will not be able to access it.

Be careful:
The lock object of non static synchronization method is this
The lock object of the static synchronization method is the bytecode object of the current class

If there is only one thread running after locking, please refer to
synchronized synchronization method \ block only one thread to execute \ run

Features of synchronization:
Synchronization: high security and low efficiency
Asynchronous: high efficiency, but low security

Posted by arion279 on Tue, 07 Apr 2020 08:55:08 -0700