Interview question 28

Source: Internet
Author: User

The sub-thread loops 10 times, then the main thread loops 100, and then returns to the sub-thread loop 10 times, and then returns to the main thread and loops 100 again, so that the loop is 50 times, please write the program.

public class TraditionalSynchronizedThread {/** * @param args */public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable(){public void run(){for (int i = 0; i < 50; i++) {business.sub(i);}}}).start();for (int i = 0; i < 50; i++) {business.main(i);}}}class Business{public boolean isSub = true;public synchronized void sub(int i){while (!isSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for (int j = 0; j < 10; j++) {System.out.println("sub thread sequece of " + "\t" + j + "\t" + ",loop of " + "\t" +i );}isSub = false;this.notify();}public synchronized void main(int i){while (isSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for (int j = 0; j < 10; j++) {System.out.println("main thread sequece of " + "\t" + j + "\t" + ",loop of " + "\t" +i );}isSub = true;this.notify();}}

1. Here we have an object-oriented approach to write related synchronous communication methods into a class.

2. Here final business = new business (); Final needs to be added, because the objects produced by business new must be included in the static methods of the internal class, and the final method needs to be added due to the lifecycle relationship.

3, Here thread synchronization knowledge reference http://blog.csdn.net/jyfllzy/article/details/6563536, pay attention to the need to use while Judge flag, specific reference Java 2 SE 6 Documentation of wait () (see the http://blog.csdn.net/ltyisangel/article/details/9496859 ), this may cause false wakeup.

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.