Introduction to Java multithreading and sample programs

  • 2020-04-01 02:37:40
  • OfStack

Why multithreading?

Simplification of the model, for example, some programs are run by multiple relatively independent tasks:

Graphical interface, input, output of the block

Better use of multi-core cpus

The need for asynchronous behavior

Java multithreading features:

The program's entry main is itself a thread

Threads are concurrent and unordered

Internally, threads execute sequentially

Shared data


Risks of multithreading in Java:

Security risk: because the sequence of operations of threads is uncertain, some programs that can run on a single thread can have unexpected results with multiple threads.

Performance risks: server throughput, responsiveness, resource consumption


Java multithreading API:

Java can create threads in two forms: to implement the Runnable interface and to inherit the Thread class.

Inherits the thread creation thread sample code


public class ThreadTest extends Thread {  

    public static void main(String[] args) {  
        ThreadTest thread = new ThreadTest();  
        thread.start();  
        for (int i=0; i<10; i++) {  
            System.out.println("main:"+i);  
        }  
    }  

    @Override  
    public void run() {  
        for (int i=0; i<10; i++) {  
            System.out.println("thread:"+i);  
        }  
    }  

}  

Implement runnable to create thread code


package com.openrdp.thread.api;  

public class RunnableTest implements Runnable {  

    public static void main(String[] args) {  
        RunnableTest runnable = new RunnableTest();  
        Thread thread = new Thread(runnable);  
        thread.start();  
        for (int i=0; i<10; i++) {  
            System.out.println("main:"+i);  
        }  
    }  

    @Override  
    public void run() {  
        for (int i=0; i<10; i++) {  
            System.out.println("thread:"+i);  
        }  
    }  

}  

Java thread pool technology

Executors to obtain exceuctorservice thread pool code


package com.openrdp.thread.api;  

import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  

public class TreadPoolTest {  
    public static void main(String[] args) {  
        ExecutorService threadPool = Executors.newFixedThreadPool(99);  
        TaskThread thread1 = new TaskThread("t1");  
        threadPool.execute(thread1);  
        TaskThread thread2 = new TaskThread("t2");  
        threadPool.execute(thread2);  

    }  

    static class TaskThread implements Runnable {  
        String param;  
        public TaskThread(String param) {  
            this.param = param;  
        }  

        @Override  
        public void run() {  

        }  
    }  
}


Related articles: