java中锁的应用(synchronized)

     在面试菜鸟的时候碰到的锁的编程问题,没答好,记录一下:

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();
    }
}

  

原文地址:https://www.cnblogs.com/spillage/p/15470879.html