在面试菜鸟的时候碰到的锁的编程问题,没答好,记录一下:
package com.xielu.test; /** * Hello world! * */ public class App { private Object lock = new Object(); private static int cnt = 1; private static final int MAX = 100; public static void main( String[] args ) { Thread th1 = new Thread(){ @Override public void run(){ synchronized(lock){ while(cnt <= MAX){ if(cnt%2 != 0){ System.out.println(cnt); cnt++; lock.notifyAll(); } else{ try{ lock.wait(); }catch(Exception e){ e.printStackTrace(); } } } } } }; Thread th2 = new Thread(){ @Override public void run(){ synchronized(lock){ while(cnt <= MAX){ if(cnt%2 == 0){ System.out.println(cnt); cnt++; lock.notifyAll(); } else{ try{ lock.wait(); }catch(Exception e){ e.printStackTrace(); } } } } } }; th1.start(); th2.start(); } }