Multiple threads implement sequential printing of data (customizable threads print quantity and total quantity at a time)

Source: Internet
Author: User

Recently saw an interview problem: let 3 threads sequentially print numbers, such as thread 1 print 1-5, thread 2 print 6-10, thread 3 print 11-15, then thread 1 print 16-20 ... Print until the end of 75.

There are two points to the main question:

The 1th is that no other threads appear during the process of printing the thread

The 2nd is that the process of thread entry is orderly, as above 123123. Such

I first implemented the basic functions, and later found that can be modified to make extensible, that is, the number of each print can be customized, the total number can be customized, and ensure that the order of threads is orderly, the following is the specific code:

Printqueue.java files, synchronizing threads, controlling the print order, is also the most important method

 PackageCom.cky;ImportJava.util.LinkedHashMap;ImportJava.util.Map; Public classPrintQueue { Public inttargetnum=0;//the number of targets to print     Public intprintonce=0;//number of times to print    Private intNownum=1;//The quantity currently printed to    /**     *      * @paramtargetnum number of targets to print *@paramprintonce number of times to print*/     PublicPrintQueue (intTargetnum,intprintonce) {        Super();  This. Targetnum =Targetnum;  This. printonce =printonce; }    Private intnextthreadnum=0;//Next time you want to execute a thread subscript    Private intthreadcount=0;//total number of threads//Map Collection, store threads, keys are specific threads, values store threads in the order in which they are printed    PrivateMap<thread,integer> threads=NewLinkedhashmap<thread,integer>(); //Add Thread     Public voidsetthread (thread thread) {threads.put (thread, threadcount); ThreadCount++; }    //Running Threads     Public voidrun () { for(Thread thread:threads.keySet ()) {Thread.Start (); }    }         Public synchronized voidPrintnum ()throwsinterruptedexception {//gets the current threadThread currentthread=Thread.CurrentThread (); //gets the current thread coordinates        intcurrentnum=Threads.get (CurrentThread); //determine if the expected thread        if(currentnum==nextthreadnum) {             for(inti=0;i<printonce;i++) {System.out.println ("Current thread:" +currentthread.getname () + ":" +nownum++); if(nownum>targetnum) {System.out.println ("Work done");  This. Wait (); }            }            //expected thread name +1nextthreadnum= (++nextthreadnum)%ThreadCount; }    }    }

Runtest.java very simple runable interface implementation, the function is to request printing

 PackageCom.cky;classRuntestImplementsrunnable{PrintQueue PS;  Publicruntest (PrintQueue PS) { This. ps=PS; } @Override Public voidrun () {Try {             while(true) {ps.printnum (); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Threaddemo.java Test class

 PackageCom.cky; Public classThreaddemo { Public Static voidmain (String [] args) {//Set print altogether 20, each thread only prints 3 at a time
PrintQueue PS=NewPrintQueue (20, 3);
Add Thread Ps.setthread (NewThread (NewRuntest (PS), "King Sledgehammer")); Ps.setthread (NewThread (NewRuntest (PS), "Zhangquan egg")); Ps.setthread (NewThread (NewRuntest (PS), "Two dogs")); Ps.run (); }}

Execution Result:

Multiple threads implement sequential printing of data (customizable threads print quantity and total quantity at a time)

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.