There are 4 threads A, B, C, D, respectively printing 1, 2, 3, 4, please start them at the same time, but required to output the results in 1234 order

Source: Internet
Author: User

1. There are 4 Threads a,B,C,D, print separately 1,2,3,4, please start them at the same time, but require to follow The sequential output of the 1234.


public class TestABCThread3 {

Private Object lock = new Object ();

private int count;


public static void Main (string[] args) {

TESTABCTHREAD3 ABC = new TESTABCTHREAD3 ();

New Thread (Abc.new Run ("C", 3)). Start ();

New Thread (Abc.new Run ("D", 4)). Start ();

New Thread (Abc.new Run ("A", 1)). Start ();

New Thread (Abc.new Run ("B", 2)). Start ();

}


Class Run implements Runnable {

Private String _name = "";

private int _threadnum;


Public Run (String name, int threadnum) {

_name = name;

_threadnum = Threadnum;

}


@Override

public void Run () {

Synchronized (lock) {

while (true) {

if (count% 4 = = _threadnum-1) {

System.out.println ("Thread-name:" + _name+ ", No:" +this._threadnum);

count++;

Lock.notifyall ();

Break

} else {

try {

Lock.wait ();

} catch (Interruptedexception e) {

E.printstacktrace ();

}

}

}


}

}

}

}


There are 4 threads A, B, C, D, respectively printing 1, 2, 3, 4, please start them at the same time, but required to output the results in 1234 order

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.