This is the 22nd day of my participation in the August Wen Challenge.More challenges in August

preface

In parallel programs with multiple threads sharing data, thread-safe code ensures that each thread can execute normally and correctly through the synchronization mechanism without data contamination and other unexpected situations. To address thread safety issues, JDK1.5 rolled out java.util.concurrent and shipped packages to address these issues.

Disadvantages of New Threads

  • The performance of a new object is poor
  • Lack of unified management of threads, unlimited new threads may compete with each other, and even occupy too many system resources, resulting in a crash orOOM

ThreadPool – ThreadPool

  • Reuse existing threads to reduce the overhead of object creation and destruction.
  • The total number of threads can be controlled to control resource utilization.
  • Avoid multi-threaded resource competition and blocking.
  • Provides additional functions, timing execution, periodic execution, monitoring, etc.

The type of thread pool

inJUCUtility classes are provided in the packageExecutorsThe scheduler object is used to create a thread pool. There are four types of thread pools that can be created:

  1. CachedThreadPool – Cacheable thread pool
  2. FixedThreadPool – a fixed length thread pool
  3. SingleThreadExecutor – Single thread pool
  4. ScheduledThreadPool – Scheduling thread pool

CachedThreadPool

public class ThreadPoolSample1 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for(int i = 1 ; i <= 1000 ; i++) {
            final  int index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run(a) {
                    System.out.println(Thread.currentThread().getName() + ":"+ index); }}); }try {
            // Give the thread enough time to run
            Thread.sleep(1000); 
        } catch(InterruptedException e) { e.printStackTrace(); } threadPool.shutdown(); }}Copy the code
  • Executors.newCachedThreadPool()Create a cacheable thread pool
  • ExecutorsScheduler object
  • ExecutorServiceUsed to manage thread pools
  • shutdown()Close the thread pool (wait for all threads to complete)
  • shutdownNow()Terminates the thread pool immediately without waiting for threads. This parameter is not recommended

The characteristics of

The characteristic of a cacheable thread pool is that it is infinitely large and can be created if there are no threads available in the pool and utilized if there are free threads

FixedThreadPool

public class ThreadPoolSample2 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        for(int i = 1 ; i <= 1000 ; i++) {
            final  int index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run(a) {
                    System.out.println(Thread.currentThread().getName() + ":"+ index); }}); }// Give the thread enough time to run
        try {
            Thread.sleep(1000); 
        } catch(InterruptedException e) { e.printStackTrace(); } threadPool.shutdown(); }}Copy the code
  • Executors.newFixedThreadPool(10)Create a thread pool that can create a fixed length

The characteristics of

A fixed-length thread pool is characterized by a fixed number of threads. Idle threads are used to execute tasks. If all threads are in use, subsequent tasks are in a waiting state. If the task is in the waiting state, the alternative waiting algorithm defaults to FIFO (first in first out) and LIFO(last in first out).

SingleThreadExecutor

public class ThreadPoolSample3 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        for(int i = 1 ; i <= 1000 ; i++) {
            final  int index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run(a) {
                    System.out.println(Thread.currentThread().getName() + ":"+ index); }}); }try {
            Thread.sleep(1000);
        } catch(InterruptedException e) { e.printStackTrace(); } threadPool.shutdown(); }}Copy the code
  • Executors.newSingleThreadExecutor()Create a single-threaded thread pool

The characteristics of

Use thread pools for ease of administration

ScheduledThreadPool

public class ThreadPoolSample4 {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool =  Executors.newScheduledThreadPool(5);
        / * delay 3 seconds to perform a Run method scheduledThreadPool. The schedule (new Runnable () {@ Override public void the Run () { System.out.println(" 3 seconds delay "); } } , 3 , TimeUnit.SECONDS); * /
        
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run(a) {
                System.out.println(new Date() + "Execution delayed 1 second, every 3 seconds"); }},1.3, TimeUnit.SECONDS); }}Copy the code
  • Executors.newScheduledThreadPool(5)Create a pool of schedulable threads
  • schedule()Delay the
  • scheduleAtFixedRate()How often to execute

The characteristics of

It can realize timing scheduling

Classic application

Database connection pool

Create a good database connection in the thread pool when the system is started, and use it to reduce the waiting time for user connection, advance the connection time to the project startup stage, and improve user experience.

conclusion

Thread-safe is different from thread-unsafe

  • Thread safety
    • Advantages: Reliability
    • Disadvantages: Slow execution
    • Usage Suggestion: Use this command when thread sharing is required
  • Thread insecurity
    • Advantages: Fast speed
    • Disadvantages: Results may not be as expected
    • Usage suggestion: Use within threads without sharing between threads

Common thread-safe/unsafe classes

Thread safety Thread insecurity
Vector ArrayList, and LinkedList
Properties HashSet, TreeSet
StringBuffer StringBuilder
HashTable HashMap