Java Multithreading for synchronization

Source: Internet
Author: User

Requirements: The child thread loops 5 times, then the main thread loops 10 times, then goes back to the child thread. So Loop 50 times.

To achieve the above requirements, in addition to the straightforward process-oriented implementation, you can consider object-oriented notation.

Depending on the original high cohesion, the operations of the child thread and the main thread are encapsulated together.

Synchronization is done through Wait () and notify ().

Class Business {Private Boolean shouldsub = true;public synchronized void sub (int. k) {if (shouldsub) {for (int i=0; i< 3} i++) {System.out.println ("sub thread inner of" + i + ", outer" + K);} Shouldsub = False;this.notifyall ();} else {try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ()}}} Public synchronized void main (int k) {if (!shouldsub) {for (int i=0; i<10; i++) {System.out.println ("main thread Inne R of "+ i +", outer "+ K";} Shouldsub = True;this.notifyall ();} else {try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ()}}}}

public class Traditionalthreadcommucation {public static void main (string[] args) {final business business = new Business ( New Thread (New Runnable () {@Overridepublic void Run () {for (int k=0; k<50; k++) {business.sub (k);}}). Start (); New Thread (New Runnable () {@Overridepublic void Run () {for (int k=0; k<50; k++) {business.main (k);}}). Start ();}}

According to the above design ideas, we will solve another problem:

There are 10,000 numbers in a file, and Java implements a multithreaded application to output this 10,000 number to 5 files without the same amount of output to each file. Required to start 10 threads, 221 groups, divided into 5 groups. Each group of two threads output the odd and even numbers in the file to a corresponding file in the group, requiring even-numbered threads to print an odd number of 10 odd-numbered threads after every 10 even-numbered thread, alternating between them. You also need to record the output progress, print the current completed quantity in the console for each 1000 number completed, and print "done" on the console after all threads have finished.

import java.io.bufferedreader;import java.io.file;import java.io.filereader;import  java.io.filewriter;import java.io.printwriter;import java.util.random;public class  Myprintbythread {public static void main (String[] args)  {try {PrintWriter  pw = new printwriter (New filewriter (New file ("Input.txt"), true); Random random = new random ();for  (int i=0 ; i<10000 ; i++ )  {pw.print (Math.Abs (Random.nextint ()%100)  +  " ");} Pw.flush ();p w.close (); Bufferedreader reader = new bufferedreader (New filereader ("Input.txt")); String str = reader.readline (); Reader.close (); String[] strs = str.split (" ");int j=0;for  (int i=0 ; i<5  ;i++)  {int records[] = new int[2000];for  (int k=0 ; k< 2000 ;  k++)  {records[k] = integer.parseint (Strs[j]); j + +;} Printwriter writer = new printwriter (New filewriter (new File ("Output" +i+ ". txt")) , true); Final business business = new business (writer, records); New Thread ( New runnable ()  {@Overridepublic  void run ()  {business.printeven ();}); New thread (new runnable ()  {@Overridepublic  void run ()  {business.printodd ();});}}  catch  (exception e)  {e.printstacktrace ();}} class business {private boolean shouldeven = true;private int[]  Subrecords;private printwriter pw;private int evenpointer = 0;private int  oddpointer = 0;public business (printwriter pw,int[] subrecords) &NBSP;{THIS.PW  = pw;this.subrecords = subrecords;} Public synchronized void printeven ()  {if  (SHOuldeven)  {if  (evenpointer <= subrecords.length)  {for  (int i=0 ;  i<10 ;)  {if  (subrecords[evenpointer] % 2 == 0)  {pw.print ( subrecords[evenpointer] +  " ");if  (evenpointer % 1000 == 0) System.out.println ("Already printed:"  + evenpointer); i++;}  evenpointer++;}} Shouldeven = false;this.notify ();}  else {try {this.wait ();}  catch  (interruptedexception e)  {e.printstacktrace ();}} Public synchronized void printodd ()  {if  (!shouldeven)  {if  (oddpointer  <= subrecords.length)  {for  (int i=0 ; i<10 ;)  {if  ( subrecords[oddpointer] % 2 != 0)  {pw.print (subrecords[oddpointer] +  "  ");if  (evenpointer % 1000 == 0) System.out.println (" Already printed: " + oddpointer); i++ ;}  oddpointer++;}} Shouldeven = true;this.notify ();}  else {try {this.wait ();}  catch  (interruptedexception e)  {e.printstacktrace ();}}}

The code has not been tested, the characteristics of friends can give me a message, spending changes in place.

Java Multithreading for synchronization

Related Article

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.