Starting 3 threads, thread 1 printing 1 to 5, thread 2 printing 5 to 10, thread 3 printing 11 to 15, then thread 1 printing 16 to 20, and so on ... Print until 30

Source: Internet
Author: User
 
Starting 3 threads, thread 1 printing 1 to 5, thread 2 printing 5 to 10, thread 3 printing 11 to 15, then thread 1 printing 16 to 20, and so on ... 
    Print until 30 public class Mainthread {private static int num;//current record number private static final int threadnum =3;//open Task thread count private static final int loopnum = number of 2;//threadnum thread loops private static final int singlethreadloopnum = 5;//single line
    Number of running tasks static {num = 0;  Public synchronized void Callbackmethod (String threadname) {for (int i = 1; I <= singlethreadloopnum;  
            i++) {System.out.println (threadname+ ":" + (++num));
            }} public void Printnum () throws interruptedexception{for (int i = 1; I <=loopNum; i++) { for (int j = 1; J <= Threadnum; j + +) {worker runnable = new Worker (this);//this the current record Count num  
                Pass to the next thread, thread thread = new Thread (runnable);
                Thread.setname ("thread" +j);  
                Thread.Start ();  
            Thread.Join ();  
 }  
        }  
    }   public static void Main (string[] args) throws interruptedexception{mainthread pc = new Mainthread (); Pc.  
    Printnum ();
    }} class Worker implements runnable{private Mainthread printcallback;
    Public Worker (Mainthread printcallback) {this.printcallback = Printcallback;
    public void Run () {Printcallback.callbackmethod (Thread.CurrentThread (). GetName ());
 }
}


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.