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.