多線程實現間隔打印

public class TestThread{
    public  synchronized void x() {
        System.out.println("rgreighreiohgioer");
        notify();
        try{
            wait();
        }catch(InterruptedException e){
            e.printStackTrace();
        }

    }

    public synchronized void y(){
        System.out.println("----------");
        notify();
        try{
            wait();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }

    public static void  main(String[] args){
        TestThread t=new TestThread();
        new ThreadA(t).start();
        new ThreadB(t).start();
    }

}

class ThreadA extends Thread{
    private TestThread t;
    public ThreadA(TestThread t){
        this.t=t;
    }
    @Override
    public void run(){
        for(int i=0;i<100;++i){
            t.x();

        }
    }
}

class ThreadB extends Thread{
    private TestThread t;
    public ThreadB(TestThread t){
        this.t=t;
    }
    @Override
    public void run(){
        for(int i=0;i<100;++i){
            t.y();

        }
    }
}

//最後還是線程阻塞了23333

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章