Threads alternately perform tasks in an orderly manner

Source: Internet
Author: User

public class test{//test public static void main (string[] args) throws Exception{object obj = new Object ()//Start two threads Thread1 T1 = new Thread1 (obj); Thread2 t2 = new Thread2 (obj); T1.start (); T2.start ();}} A thread prints 1-52class Thread1 extends Thread{private object obj;public Thread1 (Object obj) {this.obj = obj;}  public void Run () {synchronized (obj) {//print 1-52for (int i = 1; i <; i++) {System.out.print (i + ""); if (i% 2 = = 0) {// Do not forget to wake up other threads Obj.notifyall (); try{obj.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}}}}} Another thread prints the letter A-zclass Thread2 extends Thread{private object obj;public Thread2 (Object obj) {this.obj = obj;} public void Run () {synchronized (obj) {//print a-zfor (int i = 0; i <; i++) {System.out.print (char) (' A ' + i) + "");//No Can forget to wake up other threads Obj.notifyall (); try{//the last one, don't wait. if (i! =) {obj.wait ();}} catch (Interruptedexception e) {e.printstacktrace ();}}}}

Threads alternately perform tasks in an orderly manner

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.