Processes and threads

Keywords: Java thread

Processes and threads

A process (. exe) contains multiple threads, which occupy the resources of process memory
Why? It's like QQ can type and chat with others while video

There is a picture and a truth

example

Write a Java The program implements multithreading. The name of the thread is output in the thread. It is output once in 1000 milliseconds, a total of 10 times
  • Ways to implement multithreading
    1. Inherit Thread class
    2. Implement Runnable interface

  • Name of the output thread? Investigate inheritance (super)

The specific code is as follows (Runnable Implementation)

public class App02  implements Runnable{
    Thread t;
    public App02(){
       /*
        * this It represents App02, and App02 implements the Runnable interface
        * So you can pass parameters correctly
        * */
        t= new Thread(this,"Implement thread one");
        t.start();
    }

    public static void main(String[] args) {
        new App02();
    }

    public void run() {
        for (int i=0;i<10;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) { //Interrupted halfway
                e.printStackTrace();
            }
            //getName() inherits from the parent class
            System.out.println(Thread.currentThread().getName());  
        }
    }
}

Inherit Thread implementation

public class App01 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread("Inheritance thread 1");
        myThread.start();
//		  Threads are random. Sometimes start thread 1 first, and sometimes start thread 2 first
//        MyThread myThread2 = new MyThread("thread 2");
//        myThread2.start();
    }
}

class MyThread extends Thread{
    public MyThread(String threadName){
        /*assignment
         * Construction method assignment
         * setXXX assignment
         * */
        //The threadName of the super parent class. Press Ctrl and click super to reach it
        super(threadName);
    }

    @Override
    public void run() {
        //super.run();
        //System.out.println(Thread.currentThread().getName());
        for (int i=0;i<10;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) { //Interrupted halfway
                e.printStackTrace();
            }
            System.out.println(getName());  //getName() inherits from the parent class
        }
    }
}


Synchronous and asynchronous

  • When a thread accesses the same resource, pay attention to the problem of thread synchronization. If it is not synchronized, it is easy to cause the data not to be modified in time, and then it will be accessed by another thread. The data obtained is still the last data, resulting in data errors. Therefore, you need to queue up. After the first person processes the data, the second person can access it.

  • When an application calls a method that takes a long time to execute on an object, and does not want the program to wait for the return of the method, it should use asynchronous threads. In many cases, it is more efficient to use asynchronous methods.

  • Thread collaboration: it needs to be established in the case of thread synchronization

Here is an example
Production and sales occur simultaneously (set breakpoints to debug and view)
Prevent simultaneous production and sales (i.e. synchronization): synchronized

App03 (for starting threads)

public class App03 {
    public static void main(String[] args) {
        Product product = new Product();

        Thread producer = new Thread(new Producer(product));
        producer.start();

        Thread seller = new Thread(new Seller(product));
        seller.start();
    }
}

Producer

public class Producer implements Runnable{
    Product product;
    public Producer(Product product){
        this.product=product;

    }

    public void run() {
        for (int i=0;i<10;i++){
            product.produce();
        }

    }

}

Seller

public class Seller implements Runnable {
    //relation
    //roduct p = new Product();
    Product product;
    public Seller(Product product){
        this.product=product;
    }

    public void run() {
        for (int i=0;i<10;i++){
            product.sell();
        }

    }
}

Product

/*
* There is only one lock for the same object
* synchronized: Lock, instance method, only one method is called at the same time, the same object (product)
* Only when selected by the system can it run
* */
public class Product {
    public synchronized void produce(){
        System.out.println("Produce goods");
    }

    public synchronized void sell(){
        System.out.println("Selling goods");
    }
}

When synchronized is not added to the Product method, production and sales run at the same time (sales before production will occur, which is obviously not in line with the reality)

When the method of Product is added with synchronized, production and sales cannot run at the same time

How to realize that threads use the same object?

Posted by baseballkid420 on Sat, 20 Nov 2021 00:10:45 -0800