1. What is process
- When a piece of software runs in an operating system, we call it a process.
- Process is the smallest unit of operating system allocation of resources, thread is the smallest unit of operating system scheduling.
2. What are threads
- In a process, each independent function needs to run independently, then the current process needs to be divided into multiple running areas, each independent small area (small unit) called a thread. A thread is an entity of a process, the basic unit of CPU scheduling and dispatching, and a smaller unit that can run independently than a process.
- A program has at least one process, and a process has at least one thread.
3. What is multithreading
- First, let’s take a look at serial, parallel, and concurrency, which will help us understand multithreading.
- Serial: A thread executes all tasks in sequence.
- Parallel: Multiple threads execute at the same time without execution order.
- Concurrency: multiple threads that can execute at the same time, one executing, others waiting.
- A process that performs only one execution task or a thread that performs multiple execution tasks in sequence is called a single-threaded program. A process that has more than one task to execute and opens more than one thread at the same time to complete these tasks (concurrent) is called a multithreaded program.
- Multiple threads perform multiple tasks synchronously. The advantage of this method is to prevent thread clogging, improve user experience and program efficiency, but there is also a problem: multiple threads accessing the same resource and performing read and write operations at the same time may cause thread safety problems.
4. How to implement multi-threading
- There are four ways to achieve multithreading in Java, which can also be divided into two categories
- Methods existed before Java 5
- Thread_runnable (Runnable); Thread (Runnable);
- 2. Implement the Runnable interface, override the run method, no return value
- Methods that have emerged since Java 5
- 3. Implement Callable interface, rewrite call method, return value
- 4. Use thread pools
- 1. The Thread
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("my thread .....");
}
}
Copy the code
- 2. Implement the Runable interface
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("my runnable ....");
}
}
Copy the code
- 3. Implement the Callable interface
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyTask implements Callable<Integer> {
private int upperBounds;
public MyTask(int upperBounds) {
this.upperBounds = upperBounds;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for(int i = 1; i <= upperBounds; i++) {
sum += i;
}
return sum;
}
}
class Test01 {
public static void main(String[] args) throws Exception {
List<Future<Integer>> list = new ArrayList<>();
ExecutorService service = Executors.newFixedThreadPool(10);
for(int i = 0; i < 10; i++) {
list.add(service.submit(new MyTask((int) (Math.random() *
100))));
}
int sum = 0;
for(Future<Integer> future : list) {
// while(!future.isDone()) ;
sum += future.get();
}
System.out.println(sum);
}
}
Copy the code
-
4. Implement thread pools. The Java API provides an Executor framework that allows you to create different thread pools, either single-threaded or multithreaded. There are four thread pools:
- 1) newCachedThreadPool creates a cacheable thread pool
public void cacheThreadPoolTest() { ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 1; i <= 5; i++) { final int j = i; try { Thread.sleep(j * 1); } catch (InterruptedException e) { e.printStackTrace(); } cachedThreadPool.execute(()->out.println(" Thread: "+ thread.currentThread ().getName() +", execute: "+ j)); }}Copy the code
- 2) newFixedThreadPool creates a fixed-length thread pool that controls the maximum number of concurrent threads.
public void fixTheadPoolTest() { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); for (int i = 0; i < 5; i++) { final int j = i; Fixedthreadpool.execute (() -> {out.println(" Thread: "+ thread.currentThread ().getName() +", execute: "+ j); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}); }}Copy the code
- 3) newScheduledThreadPool Creates a thread pool of fixed length to support scheduled and periodic task execution.
public void sceduleThreadPoolTest() { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); Runnable r1 = () -> out.println(" Thread: "+ thread.currentThread ().getName() +", execute: 3 seconds to execute this task "); scheduledThreadPool.schedule(r1, 3, TimeUnit.SECONDS); Runnable r2 = () -> out.println(" Thread: "+ thread.currentThread ().getName() + "); scheduledThreadPool.scheduleAtFixedRate(r2, 2, 1, TimeUnit.SECONDS); Runnable r3 = () -> out.println(" Thread: "+ thread.currentThread ().getName() +", execute: common task "); for (int i = 0; i < 3; i++) { scheduledThreadPool.execute(r3); }}Copy the code
- 4) newSingleThreadExecutor creates a single threaded thread pool that only uses a single worker thread to perform tasks.
public void singleTheadExecutorTest() { ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < 5; i++) { final int j = i; SingleThreadExecutor. Execute (() - > out. Println (" Thread: "+ Thread. CurrentThread (). The getName () +", executive: "+ j)); }}Copy the code
5. What are thread safety issues
- In multi-threaded environment, and there is data sharing, the shared data accessed by one thread is modified by other threads, then the thread safety problem occurs. During the entire access process, no shared data is modified by other threads, which is thread-safe.
- If a program uses a member variable and changes the data of the member variable, there will be a data sharing problem, that is, a thread safety problem.
6. How does Java address thread safety
-
Thread synchronization is used so that shared data can only be modified by one thread at a time
- The Lock locking mechanism
Lock lock = new ReentrantLock(); lock.lock(); Try {// thread-safe operations may occur}finally{// unlock lock.unlock();Copy the code
- The synchronized keyword
} public void test02(String STR){system.out.println ("111");} public void test02(String STR){system.out.println ("111"); Synchronized (STR) {// This area can only be accessed by one thread at a time} system.out.println ("2222"); }Copy the code
-
Eliminating shared data: that is, data from multiple threads is not shared or the shared data is not modified.
- Use local variables, not member variables.
- If member variables are used, they are not modified.
The last
Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!