子線程迴圈10次,接著主線程迴圈100,接著又回到子線程迴圈10次,接著再回到主線程又迴圈100,如此迴圈50次,請寫出程式。
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、這裡有物件導向的思路,將相關的同步通訊方法寫到一個類裡面
2、這裡final Business business = new Business();需要加final,因為Business new出來的對象是要用在內部類的靜態方法裡面,由於生命週期關係需要加final方法。
3、這裡線程同步知識參考http://blog.csdn.net/jyfllzy/article/details/6563536 ,注意需要用到while判斷flag,具體參照Java 2 SE 6 documentation文檔的wait()(具體參見http://blog.csdn.net/ltyisangel/article/details/9496859),因為有可能會假喚醒。