两个线程交叉打印,一个打印数字,一个打印小写字母,结果为a1b2...y25z26

package com.banban.CeShi;


/**
 *  两个线程交叉打印,一个打印数字,一个打印小写字母,结果为a1b2...y25z26
 *
 */
public class ThreadPrint {
    private static Object lock = new Object();

    private Thread th1 =  new Thread(){
        @Override
        public void run() {
            synchronized (lock){
                for (int i = 1; i <= 26 ; i++) {
                    System.out.println(i);
                    lock.notify();
                    try{
                        Thread.sleep(1000);
                        lock.wait();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    private Thread th2 = new Thread(){
        @Override
        public void run() {
            synchronized (lock){
                for (int i = 1; i <= 26; i++) {
                    System.out.println((char)(i+64));
                    lock.notify();
                    try {
                        Thread.sleep(1000);
                        lock.wait();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    };

}

你可能感兴趣的:(每日一算法,面试题,双线程交叉打印)