Java limits the number of threads to execute

1. Use signal semaphore

1. All codes:

public class ThreadPoolTest {
    
    
    //信号里
    private static Semaphore semaphore=new Semaphore(5);//允许个数,相当于放了5把锁
    public static void main(String[] args) {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            new Thread(new Runnable() {
    
    
                public void run() {
    
    
                    method();
                }
            }).start();
        }
    }

    private static void method() {
    
    
        try {
    
    
            semaphore.acquire();//发起信号
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("ThreadName="+Thread.currentThread().getName()+"我过来了");
        try {
    
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("ThreadName="+Thread.currentThread().getName()+"出去了");
        semaphore.release();//释放信号
    }
}

2. Steps

1. Create a signal class and pass in the number of allowed threads

private static Semaphore semaphore=new Semaphore(5);//允许个数,它表示一次性允许执行5线程

2. Initiation signal and end signal:

semaphore.acquire();//发起信号
semaphore.release();//释放信号

Between the initiation and release of the signal, write the method to be executed,

try {
    
    
            semaphore.acquire();//发起信号
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("ThreadName="+Thread.currentThread().getName()+"我过来了");
        try {
    
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("ThreadName="+Thread.currentThread().getName()+"出去了");
        semaphore.release();//释放信号

2. Use the built-in thread pool class to fix the thread pool newFixedThreadPool

1. Code:

public class ThreadPoolTest2 {
    
    
    private static Executor executors=Executors.newCachedThreadPool();//缓存线程池
    private static Executor executors2=Executors.newFixedThreadPool(5);//固定线程池
    private static Executor executors3=Executors.newScheduledThreadPool(5);//缓存线程池
    private static Executor executors4=Executors.newSingleThreadExecutor();//单个线程池
    public static void main(String[] args) {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            executors2.execute(new Runnable() {
    
    
                public void run() {
    
    
                    method();
                }
            });
        }
    }

    private static void method() {
    
    
        System.out.println("ThreadName="+Thread.currentThread().getName()+"开始执行");
        try {
    
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("ThreadName="+Thread.currentThread().getName()+"执行结束");
    }
}

2. Steps:

1. Instantiate a fixed thread pool

private static Executor executors2=Executors.newFixedThreadPool(5);//固定线程池,表示一次只能执行5条子线程

2. Execution

executors2.execute(new Runnable() {
    
    
                public void run() {
    
    
                    method();
                }
            });

2. Use custom thread pool -> thread pool executor: ThreadPoolExecutor

1. Code:

public class ThreadPoolTest3 {
    
    
    public static void main(String[] args) {
    
    

        LinkedBlockingQueue<Runnable> blockingQueue=new LinkedBlockingQueue(100);//100是该容器的最大上限
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 100, 1, TimeUnit.SECONDS, blockingQueue, new ThreadFactory() {
    
    
            //线程安全的int的包装类,i++
            AtomicInteger atomicInteger=new AtomicInteger(0);

            public Thread newThread(Runnable r) {
    
    
                //创建一个线程,然后把r复制给该线程
                Thread thread = new Thread(r);
                thread.setName("MyThread"+atomicInteger.getAndIncrement());
                return thread;
            }
        });


        for (int i = 0; i < 100; i++) {
    
    
            threadPoolExecutor.execute(new Runnable() {
    
    
                public void run() {
    
    
                    method();
                }
            });
        }
    }

    private static void method() {
    
    
        System.out.println("ThreadName="+Thread.currentThread().getName()+"我过来了");
        try {
    
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("ThreadName="+Thread.currentThread().getName()+"出去了--------------------------");
    }
}

2. Steps:

1. Initialize thread pool execution

The one using five parameters

Parameter introduction
  1. corePoolSize: indicates the core thread pool (how many threads are executed at one time, here is set to 5)
  2. maximumPoolSize: The maximum number of thread pools allowed in the thread pool
  3. keepAliveTime:
  4. unit:
  5. workQueue: The workQueue is used to retain the queue of tasks before executing tasks. This queue will only store {@code Runnable} tasks submitted by the {@code execute} method.
    Schematic diagram:
    Insert picture description here

2.

3.

Guess you like

Origin blog.csdn.net/sunweihao2019/article/details/109283753
Recommended