Creation and common methods of java thread (Thread)

Process and Thread

Program: A program is an ordered collection of data and instructions. It has no meaning of running and is a static concept.

Process: It is the process of program execution. It is a dynamic concept and the unit of system resource allocation.

Threads: A process contains more threads. Of course, there is at least one thread in a process. A thread is the unit of CPU scheduling and execution;

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-D5XJ3X4Z-1660287821263) (C:\Users\FBM\AppData\Roaming\Typora\typora-user-images\ image-20220708170502917.png)]

Thread creation

Inherit Thread 2. Implement Runnable 3. Implement Callable
package demo1;
//如何创建多线程
public class strat_thread01 extends Thread{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 20000; i++) {
    
    
            System.out.println("-----------我在学习多线程");
        }
    }
    public static void main(String[] args) {
    
    
        strat_thread01 strat_thread=new strat_thread01();
        //这样的话就直接调用run方法
//        strat_thread.run();
//        这样的话就是同时开启多线程,里面的for循环是同时执行的。
        strat_thread.start();
        for (int i = 0; i < 20000; i++) {
    
    
            System.out.println("------------tongshizaixuexixianchengdeke");
        }
    }
}
Example of downloading pictures through threads
package demo1;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习多线程下载
public class strat_thread02 extends Thread{
    
    
    private String url;
    private String name;
    public strat_thread02(String url,String name){
    
    
        this.url=url;
        this.name=name;
    }
    @Override
    public void run() {
    
    
        downloadMethod download=new downloadMethod();
        download.downloadMethod1(url,name);
        System.out.println("您的图片已经下载完成:"+name);
    }
    public static void main(String[] args) {
    
    
        strat_thread02 strat_thread01=new strat_thread02("https://pics5.baidu" +
                ".com/feed/dbb44aed2e738bd4373c0e80c6341adc267ff9a8.jpeg?token=f2ab22ff3243929b141f525f8c869371",
                "image1.jpg");

        strat_thread02 strat_thread02=new strat_thread02("https://img1.baidu.com/it/u=1966616150,2146512490&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1657472400&t=2bb1ed82ca4098d830b7a9354a1ca749","image2.jpg");
        strat_thread02 strat_thread03=new strat_thread02("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1657472400&t=cf13b8c38044a363e513c33ed698bb8a",
                "image3.jpg");
        strat_thread01.start();
        strat_thread02.start();
        strat_thread03.start();
    }
}
 class downloadMethod{
    
    
//    下载方法
   public void  downloadMethod1(String url,String file){
    
    
       try {
    
    
           FileUtils.copyURLToFile(new URL(url),new File(file));
       }catch (IOException e){
    
    
           e.printStackTrace();
           System.out.println("IO异常,downloader方法出现异常!");
       }
   }
}

您的图片已经下载完成:image1.jpg
您的图片已经下载完成:image3.jpg
您的图片已经下载完成:image2.jpg  
这里可以看出来下载出来的图片完成顺序是不一致的
Implement the Runnable interface
package demo1;
//如何创建多线程
public class strat_thread03 implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 20000; i++) {
    
    
            System.out.println("-----------我在学习多线程");
        }
    }
    public static void main(String[] args) {
    
    
        strat_thread03 strat_thread=new strat_thread03();
        new Thread(strat_thread).start();

        for (int i = 0; i < 20000; i++) {
    
    
            System.out.println("------------tongshizaixuexixianchengdeke");
        }
    }
}

To start, you must first create a new Thread object, then pass in the object that implements the overridden run method, and then turn on strat();

Inheritance can only inherit one, but can implement multiple interfaces. It is recommended to use this method because it can avoid the defects of single inheritance.

Examples of ticket grabbing:
    package demo1;
    //如何创建多线程
    public class strat_thread04 implements Runnable{
    
    
        private int tiket=10;
        @Override
        public void run() {
    
    
            while (true) {
    
    
                tiket--;
                if (tiket <= 0) {
    
    
                    break;
                }
                try {
    
    
                    Thread.sleep(200);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "拿到了" + tiket + "张票");
            }
        }
        public static void main(String[] args) {
    
    
            strat_thread04 strat=new strat_thread04();
//            因为同时在运行同一个线程,所以这里会有抢占资源的情况
            new Thread(strat,"小明").start();
            new Thread(strat,"黄牛").start();
            new Thread(strat,"张三").start();
        }
    }
Tortoise and Hare:
    package demo1;
    //如何创建多线程
    public class strat_thread05 implements Runnable{
    
    
        private String winner;
        @Override
        public void run() {
    
    
            while (true) {
    
    
                for (int i = 0; i <= 100; i++) {
    
    
                    boolean isTrue =runStept(i);
                    if (Thread.currentThread().getName().equals("兔子")&&i%10==0){
    
    
                        try {
    
    
                            Thread.sleep(2);
                        } catch (InterruptedException e) {
    
    
                            e.printStackTrace();
                        }
                        System.out.println("兔子跑的太快了,休息一下");
                    }

                    System.out.println(Thread.currentThread().getName() +"跑了"+i);
                    if (isTrue){
    
    
                        break;
                    }
                }
                System.out.println("胜利者是:"+winner);
                return;

            }
        }
        public boolean runStept(int step){
    
    
            if (winner!=null){
    
    
                return true;
            }else {
    
    
                if (step==100){
    
    
                    winner=Thread.currentThread().getName();
                    return true;
                }
            }
            return false;
        }
        public static void main(String[] args) {
    
    
            strat_thread05 strat=new strat_thread05();
//            因为同时在运行同一个线程,所以这里会有抢占资源的情况
            new Thread(strat,"乌龟").start();
            new Thread(strat,"兔子").start();
        }
    }
Implement the Callable method to create a thread
package demo2;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//练习多线程下载
public class testCallable implements Callable<Boolean> {
    
    
    private String url;
    private String name;
    public testCallable(String url,String name){
    
    
        this.url=url;
        this.name=name;
    }
    @Override
    public Boolean call() throws Exception {
    
    
        downloadMethod download=new downloadMethod();
        download.downloadMethod1(url,name);
        System.out.println("您的图片已经下载完成:"+name);
        return true;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        testCallable strat_thread01=new testCallable("https://pics5.baidu" +
                ".com/feed/dbb44aed2e738bd4373c0e80c6341adc267ff9a8.jpeg?token=f2ab22ff3243929b141f525f8c869371",
                "image1.jpg");

        testCallable strat_thread02=new testCallable("https://img1.baidu.com/it/u=1966616150,2146512490&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1657472400&t=2bb1ed82ca4098d830b7a9354a1ca749","image2.jpg");
        testCallable strat_thread03=new testCallable("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1657472400&t=cf13b8c38044a363e513c33ed698bb8a",
                "image3.jpg");
        //创建执行服务
        ExecutorService es= Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> submit1 = es.submit(strat_thread01);
        Future<Boolean> submit2 = es.submit(strat_thread02);
        Future<Boolean> submit3 = es.submit(strat_thread03);
        //获取结果
        Boolean aBoolean1 = submit1.get();
        Boolean aBoolean2 = submit2.get();
        Boolean aBoolean3 = submit3.get();
        //关闭服务
    	es.shutdownNow();
    }
}
class downloadMethod{
    
    
//    下载方法
  public void  downloadMethod1(String url,String file){
    
    
      try {
    
    
          FileUtils.copyURLToFile(new URL(url),new File(file));
      }catch (IOException e){
    
    
          e.printStackTrace();
          System.out.println("IO异常,downloader方法出现异常!");
      }

  }
}

Benefits of Callable:

1. Return value can be accepted

2. Can throw exceptions

Disadvantages: Implementation is a bit more complicated than the previous two methods.

/**
 * 代理对象的总结:
 * 真是对象和代理对象都要实现同一个接口
 * 代理对象要代理真实角色

 * 好处:
 * 代理对象可以做很多真实对象做不了的事情
 * 真实对象专注做自己的事情
 */

public class Staticproxy {
    
    
    public static void main(String[] args) {
    
    
//        Weddingcompany weddingcompany=new Weddingcompany(new you());
//        weddingcompany.HappyMarry();
          new Thread(()-> System.out.println("lambada的写法")).start();
          new Weddingcompany(new you()).HappyMarry();

    }
}

interface Marry{
    
    
    void HappyMarry();
}
//这个是真是对象
class you implements Marry{
    
    

    @Override
    public void HappyMarry() {
    
    
        System.out.println("卿老师要结婚了");
    }
}
//这个是代理对象
class Weddingcompany implements Marry{
    
    
    private Marry target;
    public Weddingcompany(Marry target) {
    
    
        this.target = target;
    }

    @Override
    public void HappyMarry() {
    
    
        before();
        this.target.HappyMarry();  //这就是真是的对象
        after();
    }
    public void before(){
    
    
        System.out.println("结婚之前,收尾款");
    }
    public void after(){
    
    
        System.out.println("结婚之后,布置现场");
    }
}

Lamda expression:

Definition of functional interface:
Any interface, if it contains only an abstract method, Then it is a functional interface

For functional interfaces, we can create objects of the interface through lambda expressions

package demo3;

public class lambda {
    
    
    static class Ilikeimpi1 implements Ilike{
    
    
        @Override
        public void method() {
    
    
            System.out.println("这是lambda表达式,静态内部类");
        }
    }

    public static void main(String[] args) {
    
    
        Ilikeimpi ilikeimpi=new Ilikeimpi();
        ilikeimpi.method();

        //调用静态内部类
        Ilikeimpi1 ilikeimpi1=new Ilikeimpi1();
        ilikeimpi1.method();

        //局部内部类
        class Ilikeimpi2 implements Ilike{
    
    
            @Override
            public void method() {
    
    
                System.out.println("这是lambda表达式,局部内部类");
            }
        }
        Ilikeimpi2 ilikeimpi2=new Ilikeimpi2();
        ilikeimpi2.method();
        //匿名内部类
        Ilike ilike=new Ilike() {
    
    
            @Override
            public void method() {
    
    
                System.out.println("这是匿名内部类");
            }
        };
        ilike.method();
        Ilike ilike2 = ()->{
    
    
            System.out.println("这是lambda表达式");
        };
        ilike2.method();
        //简化lambda表达式, 如果这里的括号带参数的话是可以直接写参数的,省略括号,只能有一行代码的情况下是可以这样简化的,如果有多行就用代码块包裹
        Ilike ilike3=()->System.out.println("简化lambda表达式");
        ilike3.method();
        
    }
}
interface Ilike{
    
    
    void method();
}
class Ilikeimpi implements Ilike{
    
    

    @Override
    public void method() {
    
    
        System.out.println("这是lambda表达式");
    }
}

Thread status:

Insert image description here

Thread method:

Insert image description here

  1. Thread stopped:
package demo4;
/**
 * 停止线程的方法:
 * 不建议使用JDK官方提供的停止方法,比如stop,destroy
 * 建议使用次数,或者设置标志位去停止。
 */
public class TestStop implements Runnable{
    
    
    //在这里设置一个标志位
    public boolean flag=true;
    @Override
    public void run() {
    
    
        int i=1;
        while (flag){
    
    
            i++;
            System.out.println(i);
            System.out.println("run线程正在运行");
        }
    }
    public void stop(){
    
    
        this.flag=false;
    }
    public static void main(String[] args) {
    
    
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
    
    
            System.out.println(i);
            if (i==900){
    
    
                System.out.println("线程停止了");
                testStop.stop();
            }
        }
    }
}
  1. Thread sleep:

    Simulate network delay and amplify the occurrence of problems

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * 模拟倒计时功能
     */
    public class testSleep {
          
          
    
        public static void Sleep() throws InterruptedException {
          
          
            int i=10;
            while (true){
          
          
                Thread.sleep(1000);
                i--;
                if (i==0){
          
          
                    System.out.println("倒计时结束");
                    return;
                }
                System.out.println("倒计时:"+i);
            }
        }
        public static void main(String[] args) throws InterruptedException {
          
          
    //        System.out.println("倒计时开始:");
    //        Sleep();
            while (true){
          
          
                Date startTime=new Date(System.currentTimeMillis());
                Thread.sleep(1000);
                System.out.println("系统时间为:"+new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime=new Date(System.currentTimeMillis());
            }
    
    
        }
    }
    

Thread courtesy Yield:

  1. Pauses the currently executing thread without blocking.

  2. Convert the thread from running state to ready state.

  3. Let the CPU reschedule, courtesy may not necessarily succeed! ! Depends on the CPU mood.

package demo4;
public class TestYield {
    
    
    public static void main(String[] args) {
    
    
        myYield myYield=new myYield();
        new Thread(myYield,"A").start();
        new Thread(myYield,"B").start();
    }
}
class myYield implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程结束执行");
    }
}

The thread forces a join:

It can be understood as thread queue jumping

public class testJoin implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 200; i++) {
    
    
            System.out.println("我是Vip,我要插队"+i);
        }
    }
    public static void main(String[] args) throws InterruptedException {
    
    
        testJoin testJoin=new testJoin();
        Thread thread = new Thread(testJoin);
        thread.start();
        for (int i = 0; i < 1000; i++) {
    
    
                if (i==200){
    
    
                    thread.join();
                }
            System.out.println("mian线程在执行:"+i);
        }
    }
}

Observe the status of the thread getState:

Insert image description here

public class testState {
    
    
public static void main(String[] args) throws InterruptedException {
    
    
        Thread thread=new Thread(()->{
    
    
            for (int i = 0; i < 5; i++) {
    
    
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
            System.out.println("线程结束!!!");
        });
        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);
        //观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state);
        while (state!=Thread.State.TERMINATED){
    
    //获取线程状态只要不停止就一直输出
            Thread.sleep(100);
            state=thread.getState();//更新线程状态
            System.out.println(state);
        }
    }
}

After the thread enters the death state, it cannot be started again.

Thread priority priority:

  1. The thread scheduler decides which thread to execute based on the priority of the thread.

  2. The priority of the thread is expressed as a number 1,9 Thread.MIN_PRIORITY=1;

  3. Use the following methods to change or get the priority

    getPriority().setPriority(int xxx)

package demo4;

public class TestPriority {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Thread.currentThread().getName()+"------》"+Thread.currentThread().getPriority());
        myPriority myPriority=new myPriority();
        Thread thread1=new Thread(myPriority);
        Thread thread2=new Thread(myPriority);
        Thread thread3=new Thread(myPriority);
        Thread thread4=new Thread(myPriority);
//        Thread thread5=new Thread(myPriority);
//        thread5.setPriority(11);
//        thread5.start();
        Thread thread6=new Thread(myPriority);
        thread2.setPriority(5);
        thread3.setPriority(3);
        thread4.setPriority(1);
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread6.setPriority(Thread.MAX_PRIORITY);
        thread6.start();
        thread2.start();
        thread1.start();
        thread4.start();
        thread3.start();
    }
}
class myPriority implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+"------》"+Thread.currentThread().getPriority());
    }
}

Those with higher threads may not be executed first, it still depends on the CPU’s scheduling.

Daemon:

  1. line length divisionuse line lengthsumprotection line length

  2. The virtual machine must ensure that the user thread has completed execution

  3. The virtual machine does not need to wait for the daemon thread to complete execution.

  4. For example, record operation logs in the background, monitor memory, and wait for garbage collection. . .

public class Daemon {
    
    
    public static void main(String[] args) {
    
    
        god god=new god();
        you you=new you();
        Thread thread=new Thread(god);
        thread.setDaemon(true);  //在这里设置为守护线程
        thread.start();
        new Thread(you).start();
    }
}
class god implements Runnable{
    
    
    @Override
    public void run() {
    
    
        while (true){
    
    
            System.out.println("上帝一直守护着你");
        }
    }
}
class you implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 35600; i++) {
    
    
            System.out.println("这是我的线程,一直在运行");
        }
        System.out.println("我的线程运行完毕,goodbye");
    }
}

The result of his operation is:

First set the god thread as a daemon thread. When my thread ends running, the daemon thread will end after I end it.

Thread synchronization synchronized:

Concurrency: the same object is operated by multiple threads at the same time

In ticket grabbing events and bank withdrawal events, thread synchronization is actually a kind ofwaiting mechanism, multiple threads need to access this object at the same time Enter the waiting pool of this object to form a queue, wait for the previous thread to finish using it, and the next thread is using it.

Add a synchronized lock mechanism during access. When a thread obtains an exclusive lock on an object and occupies exclusive resources, other threads must wait to release the lock immediately after use.

But there will be some problems:

  1. Holding a lock by one thread will cause other threads that require this lock to hang;
  2. Under multi-thread competition, locking and releasing locks will cause more context switches and scheduling delays, causing performance problems;
  3. If a high-priority thread waits for a low-priority thread to release the lock, it will cause priority inversion and cause performance problems;

Note: Only modifications in the method require locks, because locks will affect efficiency, and they are not required for read-only operations.

Use the synchronized keyword:

  1. Add keywords to methods

    public synchronized void buy(){}

  2. synchronized synchronization block, the object of the lock is the amount of change, which requires addition, deletion and modification operations.

    private double account;

    synchronized(account){}

CopyOnWriteArrayList:

This collection is safe, but ArrayList is unsafe. If you want the collection to be safe, you can use CopyOnWriteArrayList.

Deadlock:

When a synchronization block holds the locks of more than two objects at the same time, and requires the resources of each other at the same time, and then a stalemate occurs, a deadlock problem may occur.

public class DeadLock{
    
    
    public static void main(String[] args) {
    
    
           Makeup makeup=new Makeup("白雪公主",0);
           Makeup makeup1=new Makeup("灰姑凉",1);
           makeup.start();
           makeup1.start();
    }
}
//镜子对象
class mirror{
    
    
}
//口红对象
class lipstick{
    
    
}
class Makeup extends Thread{
    
    
    //这里保证只能拿到一份对象,使用static关键字
    private static mirror mirror=new mirror();
    private static lipstick lipstick=new lipstick();
    public String girlFriend;
    public int choice;
    public Makeup(String girlFriend,int choice){
    
    
        this.choice=choice;
        this.girlFriend=girlFriend;
    }
    @Override
    public void run() {
    
    
        try {
    
    
            makeup();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        //化妆方法
    }
    public void makeup() throws InterruptedException {
    
    
        if (choice==0){
    
    
            synchronized (mirror){
    
    
                System.out.println(girlFriend+"拿到镜子的锁");
                Thread.sleep(1000);
                synchronized (lipstick){
    
    
                    System.out.println(girlFriend+"拿到口红的锁");
                }
            }
        }else {
    
    
            synchronized (lipstick){
    
    
                System.out.println(girlFriend+"拿到口红的锁");
                Thread.sleep(1000);
                synchronized (mirror){
    
    
                    System.out.println(girlFriend +"拿到镜子的锁");
        }}}}}

How to solve:

public void makeup() throws InterruptedException {
    
    
    if (choice==0){
    
    
        synchronized (mirror){
    
    
            System.out.println(girlFriend+"拿到镜子的锁");
            Thread.sleep(1000);
        }
        synchronized (lipstick){
    
    
            System.out.println(girlFriend+"拿到口红的锁");
        }
    }else {
    
    
        synchronized (lipstick){
    
    
            System.out.println(girlFriend+"拿到口红的锁");
            Thread.sleep(1000);
        }
        synchronized (mirror){
    
    
            System.out.println(girlFriend +"拿到镜子的锁");
        }
    }
}

Just make sure that the two objects are not under the same lock.

Four necessary conditions for deadlock to occur:

1.Mutual exclusion condition: A resource can only be used by one process at a time.
2.Request and retention conditions: When a process is blocked due to requesting resources, it will not maintain the obtained resources. put.

3.Non-deprivation condition: The resources that have been obtained by the process cannot be forcibly deprived before they are used up.

4.Cyclic waiting condition: Several processes form a head-to-tail relationship of cyclic waiting for resources.

We only need to destroy one or more of them to avoid deadlock.

LOCK lock:

public class TestLock {
    
    
    public static void main(String[] args) {
    
    
        qiangpiao qiangpiao=new qiangpiao();
        new Thread(qiangpiao).start();
        new Thread(qiangpiao).start();
        new Thread(qiangpiao).start();
    }
}
class qiangpiao implements Runnable{
    
    
    public int tiket=10;
    private final ReentrantLock lock=new ReentrantLock();
    @Override
    public void run() {
    
    
        try {
    
    
            lock.lock();
            while (true){
    
    
                if (tiket>0){
    
    
                    System.out.println(tiket);
                    tiket--;
                }else {
    
    
                    break;
                }
            }
        }finally {
    
    
            lock.unlock();
        }
    }
}

Comparison between synchronized and lock locks:

Lock is an explicit lock (manually open and close the lock, don't forget to close the lock) synchronized is an implicit lock, which is automatically released when out of scope
Lock only has code block locks and synchronized There are code block locks and method locks
Using Lock locks, the JVM will spend less time scheduling threads (better performance. And have better scalability (provide more subclasses) )
Priority order:
Lock > Synchronized code block (has entered the method body and allocated corresponding resources) > Synchronized method (between the method body outside)

Producer-consumer pattern (thread collaboration):

package demo6;

public class testPC {
    
    
    public static void main(String[] args) {
    
    
        container container=new container();
        new producer(container).start();
        new customer(container).start();
    }
}
//生产的食物
class chicken{
    
    
    int id;
    public chicken(int id) {
    
    
        this.id = id;
    }
    @Override
    public String toString() {
    
    
        return "chicken{" +
                "id=" + id +
                '}';
    }
}
//生产者
class producer extends Thread{
    
    
    container container;
    public producer(container container) {
    
    
        this.container = container;
    }
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            try {
    
    
                System.out.println("生产了"+i+"只鸡");
                chicken chic=new chicken(i);
                container.push(chic);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

//消费者
class customer extends Thread{
    
    
    container container;
    public customer(container container) {
    
    
        this.container = container;
    }
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            try {
    
    
                System.out.println("消费了"+container.pop().id +"只鸡");
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

//缓冲区
class container{
    
    
    //这里的作用是一直循环将new出来的chicken对象装入
    chicken[] chickens=new chicken[10];
    int count=0;
    //生产鸡肉
    public synchronized void push(chicken chicken) throws InterruptedException {
    
    
        //如果里面满了的话就通知等待
        if(count==chickens.length){
    
    
            this.wait();
        }else {
    
    
            //往里面放入鸡肉
            chickens[count]=chicken;
            count++;
            //这里是通知消费者消费
            this.notify();
        }
    }
    public synchronized chicken pop() throws InterruptedException {
    
    
        //如果消费完了就让消费者等待
        if (count == 0) {
    
    
            this.wait();
        }
            //往里面放入鸡肉
            count--;
            chicken chicken1 = chickens[count];
            //这里是通知消费者消费
            this.notify();
        return chicken1;
    }
}

Signal light method:

public class testPC1 {
    
    
    public static void main(String[] args) {
    
    
        TV tv=new TV();
        new player(tv).start();
        new watch(tv).start();
    }
}
class player extends Thread{
    
    
    TV tv;

    public player(TV tv) {
    
    
        this.tv = tv;
    }
    @Override
    public void run() {
    
    
        for (int i = 0; i < 20; i++) {
    
    
                if (i%2==0){
    
    
                    try {
    
    
                        this.tv.playerMethod("快乐大本营!!!");
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }else{
    
    
                    try {
    
    
                        this.tv.playerMethod("抖音记录美好生活!!!");
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }
        }
    }
}
class watch extends Thread{
    
    
    TV tv;
    public watch(TV tv) {
    
    
        this.tv = tv;
    }
    @Override
    public void run() {
    
    
        for (int i = 0; i < 20; i++) {
    
    
            try {
    
    
                tv.watchMethod();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}
class TV{
    
    
    String movie;
    boolean flag=true;
    //表演方法
    public synchronized void playerMethod(String movie) throws InterruptedException {
    
    
        if (!flag){
    
    
            this.wait();
        }
        System.out.println("演员表演了:"+movie);
        this.notify();   //通知观看
        this.movie=movie;
        this.flag=!this.flag;
    }
    //观看方法
    public synchronized void watchMethod() throws InterruptedException {
    
    
        if (flag){
    
    
            this.wait();
        }
        System.out.println("观众观看了:"+movie);
        this.notify();
        this.flag=!this.flag;
    }
}

Use thread pool:

Background: Resources that are frequently created and destroyed with particularly large amounts of usage, such as threads in concurrent situations, have a great impact on performance.

Idea: Create multiple threads in advance, put them into the thread pool, obtain them directly when used, and put them into the thread pool after use. This can avoid repeated creation and destruction and achieve reuse, similar to public transportation in life.

benefit:

  1. Improved performance (reduced time to create new threads)

  2. Reduce resource consumption

  3. Facilitates thread management

    corePoolSize: the size of the core pool;

    maxmumPoolSize: maximum number of threads;

    keepAliveTime: The maximum length of time a thread can keep before it stops when it has no tasks;

/**
 * 测试线程池
 */
public class TestPool {
    
    
    public static void main(String[] args) {
    
    
        int i = 10;
        ExecutorService service= Executors.newFixedThreadPool(i);
        service.execute(new Pool());
        service.execute(new Pool());
        service.execute(new Pool());
        service.execute(new Pool());
        service.shutdown();
    }
}
class Pool implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName());
      }
}

Guess you like

Origin blog.csdn.net/qq_14930709/article/details/126304573