一道很經典的線程筆試題-子線程打印30次,主線程打印20次,如此一輪,循環50輪。ide
第一種方法this
public class Test{ private boolean isSub = true; public synchronized void sub(int i){ while(!isSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j=1;j<=30;j++){ System.out.println("--------------------子線程執行第"+i+"輪,第"+j+"次。"); } isSub = false; this.notify(); } public synchronized void master(int i){ while(isSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j=1;j<=20;j++){ System.out.println("主線程執行第"+i+"輪,第"+j+"次。"); } isSub = true; this.notify(); } public static void main(String[] args) { Test t = new Test(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for(int i=1;i<=50;i++){ t.sub(i); } } }).start(); for(int i=1;i<=50;i++){ t.master(i); } } }
第二種方法spa
public class ThreadTest { private static Object object = new Object(); public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub new Thread(new Runnable() { public void run() { // TODO Auto-generated method stub for (int i = 1; i <= 50; i++) { synchronized (object) { for (int j = 1; j <= 30; j++) { System.out.println("--------------------子線程執行第"+i+"輪,第"+j+"次。"); } object.notify(); try { object.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }).start(); for(int i = 1; i <= 50; i++){ synchronized (object) { object.wait(); for (int j = 1; j <= 20; j++) { System.out.println("主線程執行第"+i+"輪,第"+j+"次。"); } object.notify(); } } } }