两个线程交叉打印1-100

public class Test {

    public static void main(String[] args) {
        Number num=new Number();
        Thread t1=new Thread(num);
        Thread t2=new Thread(num);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();

    }

}
class Number implements Runnable{
    private int i=1;
    public void run() {
        while(i<=100){
            synchronized (this) {
          //获取指定线程名称 System.out.println(Thread.currentThread().getName()
+"-----"+i); i++; notify(); try{ if(i<=100){ wait(); } }catch(Exception e){ e.printStackTrace(); } } } } }


//如果需要唤醒指定线程,可以用LockSupport park 和 unpark方法
//LockSupport.park();
//LockSupport.unpark(t2);
 
原文地址:https://www.cnblogs.com/foreverstudy/p/14665665.html