Processes and threads

1. What is process?

A process is an application that is currently running in the system

2. What are threads?

A thread is a line that executes independently within a process to perform some function.

3. Use Tencent computer butler to help understand

The relationship between processes and threads

  • A process may have multiple threads, or at least one thread
  • A thread must belong to a process
  • A process is the smallest unit of resource allocation by the operating system, and a thread is the smallest unit of resource allocation by the CPU.

Threads in Java

Thread scheduling in Java is preemptive scheduling. The higher the priority, the more likely it is to get CPU time slice execution. If the priority is the same, a random thread is selected to execute.

Two ways to create threads in Java

1. The Thread

Thread is a Thread class defined in Java. We create our own class, inherit Trhead, and override the run () method of Thread after setting up Thread tasks. Call the start() method, and the thread enters the ready state.

Code implementation

Public class Thread creation method 01 extends Thread{// Override run to set a Thread task. What are you going to do with this thread? @Override public void run() { for (int i = 0; i < 10; I ++) {system.out.println (" not easy frank"+ I); }} public static void main(String[] args) {thread creation 01 thread creation 01(); // Create thread thread.start(); // Start thread}}Copy the code

The results showed

2. Implement the Runnable interface

Public implements Runnable {@override public void run() {for (int I = 0; i < 10; I ++) {system.out.println (" implement Runnable interface "+ I); }} public static void main(String[] args) { Classes that implement Runnable cannot be instantiated as threads directly. They must be used as constructor arguments to the Thread class Thread = new Thread(new Thread creation 02()); // Create thread thread.start(); // Start thread}}Copy the code

The results showed

Java multithreading common methods

Note: Common methods have been bold

Serial number methods instructions
1 public void start() Causes the thread to start executing; The Java virtual machine calls the run method of this thread.
2 public void run() If the thread is constructed using a separate Runnable run object, the Runnable object’s run method is called. Otherwise, the method does nothing and returns.
3 public final void setName(String name) Change the thread name to be the same as the parameter name.
4 public final void setPriority(int priority) Changes the priority of a thread.
5 public final void setDaemon(boolean on) Mark this thread as a daemon thread or a user thread.
6 public final void join(long millisec) The maximum time to wait for this thread to terminate is Millis milliseconds.
7 public void interrupt() Interrupt the thread.
8 public final boolean isAlive() Tests whether the thread is active.
9 public static void yield() Suspends the currently executing thread object and executes the other threads.
10 public static void sleep(long millisec) Hibernates (suspends execution) the currently executing thread for a specified number of milliseconds, subject to the precision and accuracy of the system timer and scheduler.
11 **public static Thread currentThread() ** Returns a reference to the thread object currently executing.

4. Thread safety

1. What are thread safety issues?

  • Thread-safety issues occur when shared data is accessed by multiple threads

For example

Cinemas sell tickets. If one window sells all the tickets, there will be no problem, but if multiple Windows sell the same 1-100 tickets, there will be a situation of selling duplicate tickets and non-existent tickets

Public class MovieHouse implements Runnable {private int ticket = 100; /** * public class MovieHouse implements Runnable {private int ticket = 100; @Override public void run() { while (true) { if(ticket>0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } String threadName = Thread.currentThread().getName(); System.out.println(threadName + "selling ---->" + ticket +" ticket "); ticket--; }}}}Copy the code

The test class

Public static void main(String[] args) {MovieHouse MovieHouse = new MovieHouse(); Thread thread1 = new Thread(movieHouse); Thread thread2 = new Thread(movieHouse); Thread thread3 = new Thread(movieHouse); thread1.start(); thread2.start(); thread3.start(); }}Copy the code

Running discovery results in duplicate tickets coming out

Address thread safety issues

Thread synchronization mechanism can be solved! There are three ways to implement synchronization

Put the code that needs to access the shared data into a synchronized code block

Public class MovieHouse implements Runnable {private int ticket = 100; /** * public class MovieHouse implements Runnable {private int ticket = 100; Object obj = new Object(); @Override public void run() { while (true) { synchronized (obj) { if (ticket > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } String threadName = Thread.currentThread().getName(); System.out.println(threadName + "selling ---->" + ticket +" ticket "); ticket--; } } } } }Copy the code

After running the code, you can see that the problem of selling tickets is repeated and no tickets exist has been solved

If you define a method, decorated with Synchronize, the code in the method implements synchronization

Public class MovieHouse implements Runnable {private int ticket = 100; /** * public class MovieHouse implements Runnable {private int ticket = 100; Object obj = new Object(); @Override public void run() { saleTicket(); } public synchronized void saleTicket(){while (true) {if (ticket > 0) {try {thread.sleep (10); } catch (InterruptedException e) { e.printStackTrace(); } String threadName = Thread.currentThread().getName(); System.out.println(threadName + "selling ---->" + ticket +" ticket "); ticket--; }}}}Copy the code

After running the code, you can see that the problem of selling tickets is repeated and no tickets exist has been solved

Using the Lock interface

Public class MovieHouse implements Runnable {private int ticket = 100; /** * public class MovieHouse implements Runnable {private int ticket = 100; Lock l = new ReentrantLock(); @override public void run() {while (true) {Override public void run() {Override public void run() { if (ticket > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } String threadName = Thread.currentThread().getName(); System.out.println(threadName + "selling ---->" + ticket +" ticket "); ticket--; } // lock l.nlock (); }}}Copy the code

After running the code, you can see that the problem of selling tickets is repeated and no tickets exist has been solved

Interthread communication

  • This is the use of notify and wait methods
  • Notice that notify and wait are both methods of the Object class, and any Object has both methods.
  • It is important to remember why thread safety occurs. When multiple threads operate on shared data! Who calls notify and wait? Of course is the need to share this data!

Understanding thread pools

Thread pool is a container, usually using ArrayList or LinkedList, the generic type is Thread to store multiple threads, when we need to use directly from the container can be used, after use, put back, so as to avoid frequent creation and destruction of threads, greatly improve the efficiency of the program!

Ps:

Small white learning stage, learning is not easy, if the article has mistakes hope to be able to criticize pointed out, thank you! Come on!