多线程面试题 两个线程依次打印1、2、3...等有序的数字创建自定义类及定义属性创建线程打印输出输出结果 两个线程依次打印1、2、3…等有序的数字 创建自定义类及定义属性 /** * 创建自定义类(用来加锁) */ public class Num{ public int i = 1; //记录打印的数值 public boolean flag = false; //记录当前那个线程 可使用int类型记录更多线程 } 创建线程打印输出 public class Test(){ public static void main(String[] args) throws Exception { int count = 101; //定义打印多少次 Num num = new Num(); Thread t1 = new Thread(()->{ try { while(num.i < count){ synchronized(num){ if(num.flag){ num.wait(); }else{ System.out.println(Thread.currentThread().getName() + "___" + num.i); num.i++; num.flag = true; num.notify(); } } } } catch (Exception e) { e.printStackTrace(); } }); Thread t2 = new Thread(()->{ try{ while(num.i < count){ synchronized(num){ if(!num.flag){ num.wait(); }else{ System.out.println(Thread.currentThread().getName() + "___" + num.i); num.i++; num.flag = false; num.notify(); } } } } catch (Exception e) { e.printStackTrace(); } }); t1.setName("thread_1"); t2.setName("thread_2"); t1.start(); t2.start(); } } 输出结果