Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Java multithreading concurrency

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to achieve Java multithreading concurrency". In daily operations, I believe many people have doubts about how to achieve Java multithreading concurrency. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to achieve Java multithreading concurrency". Next, please follow the editor to study!

Inherit the Thread class

The Thread class is essentially an instance that implements the Runnable interface and represents an instance of a thread. The only way to start a thread is through the start () instance method of the Thread class. The start () method is a native method that starts a new thread and executes the run () method.

Public class MyThread extends Thread {

Public void run () {

System.out.println ("MyThread.run ()")

}}

MyThread myThread1 = new MyThread ()

MyThread1.start ()

Implement the Runnable interface

If your own class already extends another class, you cannot directly extends Thread, at this point, you can implement a Runnable interface.

Public class MyThread extends OtherClass implements Runnable {

Public void run () {

System.out.println ("MyThread.run ()")

} / / start

MyThreadMyThread myThread = new MyThread ()

Thread thread = new Thread (myThread)

Thread.start ()

Target.run () public void run () {

If (target! = null) {

Target.run ()

}}

ExecutorService, Callable, Future have return value threads

Tasks with return values must implement the Callable interface; similarly, tasks with no return values must implement the Runnable interface. After executing the Callable task, you can get an object of Future, and call get on this object to get the Object returned by the Callable task. Combined with the thread pool interface ExecutorService, you can realize the legendary multithreading that returns results.

/ / create a thread pool

ExecutorService pool = Executors.newFixedThreadPool (taskSize)

/ / create multiple tasks with return values

List list = new ArrayList ()

For (int I = 0; I < taskSize; iTunes +) {

Callable c = new MyCallable (I + "")

/ / perform the task and get the Future object

Future f = pool.submit (c); list.add (f)

} / / close thread pool pool.shutdown ()

/ / get the running results of all concurrent tasks for (Future f: list) {

/ / get the return value of the task from the Future object and output it to the console System.out.println ("res:" + f.get () .toString ())

}

Thread pool-based approach

Threads and database connections are very valuable resources. If you create it every time you need it and destroy it when you don't need it, it's a waste of resources. Then we can use the caching strategy, that is, using thread pools.

/ / create thread pool ExecutorService threadPool = Executors.newFixedThreadPool (10)

While (true) {threadPool.execute (new Runnable ()) {

/ / submit multiple threads to execute @ Override public void run () {

System.out.println (Thread.currentThread (). GetName () + "is running.")

Try {

Thread.sleep (3000)

}

Catch (InterruptedException e) {

E.printStackTrace ()

});}}

2 synchronous lock and deadlock

Synchronous locks are prone to problems when multiple threads access the same data at the same time. In order to avoid this situation, we need to ensure that threads are mutually exclusive, that is, multiple threads executing concurrently are allowed to access shared data only one thread at a time. The synchronized keyword can be used in Java to acquire a synchronization lock for an object.

What a deadlock is a deadlock is that multiple threads are blocked at the same time, and one or all of them are waiting for a resource to be released.

3 thread pool principle

The main job of the thread pool is to control the number of running threads, put the tasks in the queue during the process, and then start these tasks after the thread is created. If the number of threads exceeds the maximum number of threads waiting in line, wait for other threads to finish execution, and then take the task out of the queue to execute. The main features are: thread reuse; control the maximum number of concurrency; manage threads.

A class where a thread reuses an Thread has a start method. The Java virtual machine calls the run method of the class when start is called to start the thread. Then the run () method of the Runnable object is called in the run () method of this class. We can inherit and override the Thread class by adding a Runnable object passed through recurring calls to its start method. This is how thread pools are implemented. The continuous acquisition of Runnable in the loop method is implemented in Queue and can be blocked before getting the next Runnable.

The general thread pool is divided into the following four components:

(1) Thread pool manager: used to create and manage thread pools. (2) worker thread: a thread in a thread pool. (3) Task interface: the interface that each task must implement for the worker thread to schedule its execution. (4) Task queue: it is used to store tasks to be processed and provides a buffering mechanism.

Thread pooling in Java is implemented through the Executor framework, which uses classes such as Executor,Executors,ExecutorService,ThreadPoolExecutor, Callable, Future and FutureTask.

The construction method of ThreadPoolExecutor is as follows:

Public ThreadPoolExecutor (int corePoolSize,int maximumPoolSize, long keepAliveTime,TimeUnit unit, BlockingQueue workQueue) {this (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory (), defaultHandler);}

CorePoolSize: specifies the number of threads in the thread pool.

MaximumPoolSize: specifies the maximum number of threads in the thread pool.

KeepAliveTime: when the current thread pool exceeds corePoolSize, the survival time of excess idle threads, that is, multiple times, will be destroyed.

The unit of unit:keepAliveTime.

WorkQueue: task queue, tasks that have been submitted but not yet executed.

ThreadFactory: thread factory, used to create threads, usually with the default.

Handler: reject strategy, how to reject a task when there are too many tasks to deal with.

The threads in the deny policy thread pool have been used up and can no longer serve new tasks, and at the same time, the waiting queue is full and there is no room for new tasks. At this time, we need to reject the strategy mechanism to deal with this problem reasonably.

The built-in rejection policies for JDK are as follows:

AbortPolicy: throw an exception directly to prevent the system from running normally.

CallerRunsPolicy: this policy runs the currently discarded task directly in the caller thread as long as the thread pool is not closed. Obviously, this will not actually discard the task, but the performance of the task submission thread is likely to deteriorate sharply.

DiscardOldestPolicy: discard the oldest request, a task that is about to be executed, and try to submit the current task again.

DiscardPolicy: this policy silently discards tasks that cannot be handled without any processing. This is the best solution if tasks are allowed to be lost.

The above built-in rejection policies all implement the RejectedExecutionHandler API. If the above policies still cannot meet the actual needs, you can extend the RejectedExecutionHandler API yourself.

Java thread pool work process (1) when the thread pool was first created, there was no thread in it. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool does not execute them immediately.

(2) when the execute () method is called to add a task, the thread pool will make the following judgment:

A) if the number of running threads is less than corePoolSize, create a thread to run the task immediately

B) if the number of running threads is greater than or equal to corePoolSize, put the task in the queue

C) if the queue is full and the number of running threads is small maximumPoolSize, create a non-core thread to run the task immediately

D) if the queue is full and the number of running threads is greater than or equal to maximumPoolSize, the thread pool will throw an exception RejectExecutionException.

(3) when a thread completes a task, it takes the next task from the queue to execute.

(4) when a thread has nothing to do for more than a certain amount of time (keepAliveTime), the thread pool will judge that if the number of currently running threads is greater than corePoolSize, then the thread will be stopped. So when all the tasks in the thread pool are completed, it will eventually shrink to the size of corePoolSize.

At this point, the study on "how to achieve Java multithreading concurrency" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report