一道很经典的线程笔试题-子线程打印30次,主线程打印20次,如此一轮,循环50轮。
一道很经典的线程笔试题-子线程打印30次,主线程打印20次,如此一轮,循环50轮。
第一种方法
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); } } }
第二种方法
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(); } } } }