Is Java multithreading efficient?

Source: Internet
Author: User

I haven't been here for a long time. I found that although I read a lot of materials and books, it is easy to forget things I haven't touched for a long time. We hope to record more records in the future.

Today, I played the thread pool, made some adjustments to the parameters, and recorded the response of the number of threads to various situations in the case of multiple concurrency. The program was found online and slightly modified.

Java thread pool implementation, threadpool

 

Package net. ZJ. hz. yk. threadpool; </P> <p> Import Java. util. writable list; </P> <p> public class threadpool extends threadgroup {<br/> private Boolean isclosed = false; // whether the thread pool is closed <br/> private writable list workqueue; // work queue <br/> Private Static int threadpoolid = 1; // thread pool id </P> <p> Public threadpool (INT poolsize) {<br/> super (threadpoolid + ""); // specify the threadgroup name <br/> setdaemon (true); // The inherited method, set whether to daemon thread pool <br/> Workqueue = new queue list (); // create a work queue <br/> for (INT I = 0; I <poolsize; I ++) {<br/> New workthread (I ). start (); // create and start a working thread, A worker thread is created when the number of thread pools is equal to <br/>}</P> <p>/** wait for the worker thread to put all tasks execution completed */<br/> Public void waitfinish () {<br/> synchronized (this) {<br/> isclosed = true; <br/> policyall (); // wake up all tasks that are still in gettask () the worker thread waiting for the task in the method <br/>}< br/> // activecount () returns the estimated value of the active thread in the thread group. <Br/> thread [] threads = new thread [activecount ()]; <br/> // The enumerate () method inherits from the threadgroup class, obtain all active working threads in the thread group based on the estimated value of the active thread <br/> int COUNT = enumerate (threads); <br/> for (INT I = 0; I <count; I ++) {// wait for all worker threads to end <br/> try {<br/> threads [I]. join (); // wait until the worker thread ends <br/>} catch (interruptedexception ex) {<br/> ex. printstacktrace (); <br/>}</P> <p>/** disable thread pool */<br/> Public synchronized void closepool () {<Br/> If (! Isclosed) {<br/> // wait for the worker thread to finish running <br/> waitfinish (); <br/> isclosed = true; <br/> // clear a work queue <br/> workqueue. clear (); <br/> // Interrupt all worker threads in the thread pool. This method inherits from the threadgroup class <br/> interrupt (); <br/>}</P> <p>/** Add a new task to the work queue, the worker thread executes the task */<br/> Public synchronized void execute (runnable task) {<br/> If (isclosed) {<br/> throw new illegalstateexception (); <br/>}< br/> If (task! = NULL) {<br/> // Add a task to the queue <br/> workqueue. add (task); <br/> // wake up a worker thread waiting for the task in the gettask () method <br/> running y (); <br/>}</P> <p>/** retrieve a task from the work queue, the worker thread calls this method */<br/> private synchronized runnable gettask (INT threadid) <br/> throws interruptedexception {<br/> while (workqueue. size () = 0) {<br/> If (isclosed) {<br/> return NULL; <br/>}< br/> system. out. println ("working thread" + threadid + "waiting for task... "); <br/> wait ();/ /If there are no tasks in the work queue, wait for the task <br/>}< br/> system. out. println ("worker thread" + threadid + "start to execute the task... current task count: "<br/> + workqueue. size (); <br/> // returns the first element in the queue and deletes the <br/> return (runnable) workqueue from the queue. removefirst (); <br/>}</P> <p>/** <br/> * internal class, working thread, which extracts tasks from the working queue, run <br/> * @ author sunnylocus <br/> */<br/> private class workthread extends thread {<br/> private int ID; </P> <p> Public workthread (int id) {<br/> // constructor of the parent class To add the thread to the current threadpool thread group <br/> super (threadpool. this, ID + ""); <br/> This. id = ID; <br/>}</P> <p> Public void run () {<br/> while (! Isinterrupted () {// The isinterrupted () method inherits from the Thread class to determine whether the thread is interrupted <br/> runnable task = NULL; <br/> try {<br/> task = gettask (ID); // retrieve the task <br/>} catch (interruptedexception ex) {<br/> ex. printstacktrace (); <br/>}< br/> // If gettask () returns NULL or is interrupted when the thread executes gettask, end this thread <br/> If (task = NULL) <br/> return; </P> <p> try {<br/> taketimeoperation (); <br/> // This. sleep (5000); <br/> task. run (); // run the task <br/>} catch (throwable t) {<br/> T. printstacktrace (); <br/>}< br/>}// end while <br/>}// end run <br/>}// end workthread </P> <p>/ /time-consuming operations, A <br/> private void taketimeoperation () {<br/> int I = 0; <br/> string test = ""; <br/> while (I <threadpooltest. taketime_num) {<br/> test + = "" + I; <br/> I ++; <br/>}</P> <p >}< br/>

 

Test class:

Package net. ZJ. hz. yk. threadpool; </P> <p> public class threadpooltest {</P> <p> // Number of threads <br/> Private Static final int thread_num = 2; </P> <p> // number of tasks <br/> Private Static final int task_num = 15; </P> <p> // time-consuming operation time <br/> Public static final int taketime_num = 5500; </P> <p> Public static void main (string [] ARGs) throws interruptedexception {<br/> long begintime = system. currenttimemillis (); <br/> // create a thread pool with thread_num working threads. <br/> threadpool = new threadpool (thread_num ); <br/> // sleep for 500 milliseconds to make all worker threads in the thread pool run <br/> thread. sleep (500); <br/> // run the task <br/> for (INT I = 0; I <= task_num; I ++) {// create task_num tasks <br/> threadpool.exe cute (createtask (I); <br/>}< br/> threadpool. waitfinish (); // wait until all tasks are completed <br/> threadpool. closepool (); // close the thread pool <br/> long endtime = system. currenttimemillis (); <br/> system. out. print ("***** current thread count:" + thread_num + ", ******* shared time:" + (endtime-begintime )); </P> <p >}</P> <p> Private Static runnable createtask (final int taskid) {<br/> return New runnable () {<br/> Public void run () {<br/> // system. out. println ("task" + taskid + "start"); <br/> system. out. println ("Hello World"); <br/> // system. out. println ("task" + taskid + "end"); <br/>}< br/> }; <br/>}</P> <p >}< br/>

 

1. if the thread is time-consuming but not CPU-consuming, it is taketimeoperation () in the workthread of threadpool. Comment out this line and set this. sleep (5000); open. The test results are as follows:

***** Current thread count: 3, ****** sharing time: 30516
***** Number of threads: 6, ****** share time: 15516
***** Current thread count: 12, ****** sharing time: 10516
***** Number of current threads: 24, ****** sharing time: 5500
***** Number of threads: 16, ****** share time: 5500

 

It can be found that the increase in the number of threads significantly improves the system performance. When the number of threads is equal to the number of tasks, it makes no sense if the number of threads is higher than the number of tasks.

 

2. If the thread operation is time-consuming and CPU-consuming, taketimeoperation () is enabled in the workthread of threadpool. In this line, this. Sleep (5000); is commented out. The results of testing with 16 tasks are as follows:

***** Current thread count: 1, ****** sharing time: 4344
***** Current thread count: 2, ****** sharing time: 3828
***** Current thread count: 3, ****** sharing time: 4297
***** Number of threads: 6, ****** share time: 4453
***** Current thread count: 12, ****** sharing time: 4875

***** Number of threads: 16, ****** share time: 5062

 

It can be found that the number of threads is increased, and the system performance is reduced. When the number of threads is 2, the performance is the best. It is estimated that my CPU is the reason of dual-core. When the thread is set to 1, the CPU utilization is not high. When the thread is too large, the CPU performance is difficult to improve because its pressure has reached the bottleneck, however, the processing speed is estimated to be slow. The thread itself also requires overhead. Of course, it uses the pool technology, that is, it will be slower when it is created for the first time. If it is obtained from the pool, the overhead on performance will be minimal. However, threads occupy the memory. If the thread pool is too large, there is a risk of memory overflow.

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.