Implementation of multithreading

Posted by atomm on Sun, 23 Jan 2022 10:14:03 +0100

Multithreading

The concept of multithreading

When do I need multithreading
● the program needs to perform two or more tasks at the same time.
● when the program needs to realize some tasks that need to wait, such as user input, file reading and writing operation, network operation, search, etc.
● when some background programs are required.

Advantages of multithreading
● improve program response
● improve CPU utilization
● improve the program structure, divide complex tasks into pairs of threads and run independently

Disadvantages of multithreading
● threads are also programs, so threads need to occupy memory. The more threads, the more memory they occupy;
● multithreading needs coordination and management, so CPU time is required to track threads;
● the access to shared resources between threads will affect each other, and the problem of competing for shared resources must be solved;

Thread synchronization

Multithread synchronization
● conflicts may occur when multiple threads read and write the same shared resource at the same time. Therefore, the "synchronization" mechanism of threads is introduced, that is, there should be first come, first served between threads;

Synchronization is queue + lock:
● queue up among several threads to operate the shared resources one by one, rather than at the same time;
● in order to ensure the correctness of data accessed in the method, a lock mechanism is added during access

synchronized
● ensure that only one thread accesses shared resources at a point in time. You can add a lock to a shared resource. Which thread has obtained the lock before it has the right to access the shared resource.
● synchronization in Java code:
Use the synchronized keyword to synchronize methods or code blocks.
Synchronized {/ / code to be synchronized;} Synchronized can also be placed in the method declaration to represent the whole method, which is a synchronized method.

The two simulated ticket selling windows sell tickets respectively, with 10 tickets, which are realized by inheriting Thread and realizing Runnable respectively

Inherit Thread implementation:

public class ThreadDemo4 extends Thread {
          static  int num=10;
          static Object object =new Object();
    @Override
    public void run() {
        while (true) {
            synchronized (object) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + "Get the first" + num + "Ticket");
                    num--;
                }
                else{
                    break;
                }
            }
        }
    }
    public static void main(String[] args) {
       ThreadDemo4 threadDemo=new ThreadDemo4();
       threadDemo.setName("Ticket No. 1");
       threadDemo.start();

       ThreadDemo4 threadDemo1=new ThreadDemo4();
       threadDemo1.setName("Ticket number two");
       threadDemo1.start();
    }
}

Implementation of Runnable mode
synchronized:

public class ThreadDemo5 implements Runnable {
    static int sum = 10;

    @Override
    public void run() {
            while (true) {
                synchronized (this) {
                try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                if (sum > 0) {
                   
                    System.out.println(Thread.currentThread().getName() + "Take the first" + sum + "Ticket");
                     sum--;
                }else{
                    break;
                }
            }
        }
    }
        public static void main (String[]args){
            ThreadDemo5 threadDemo5 = new ThreadDemo5();
            Thread t1 = new Thread(threadDemo5, "Window one");
            Thread t2 = new Thread(threadDemo5, "Window II");
            t1.start();
            t2.start();
        }
    }

Lock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo6 implements Runnable {
    static int sum = 10;
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            while (true) {
                lock.lock();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (sum > 0) {
                    System.out.println(Thread.currentThread().getName() + "Take the first" + sum + "Ticket");
                    sum--;
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//Release the lock in finally
        }
    }

    public static void main(String[] args) {
        ThreadDemo5 threadDemo6 = new ThreadDemo5();
        Thread t1 = new Thread(threadDemo6, "Window one");
        Thread t2 = new Thread(threadDemo6, "Window II");
        t1.start();
        t2.start();

    }
}

Topics: Java Multithreading