java 线程方法 ---- wait()

 

class MyThread5 implements Runnable{

    private int flag = 10;

    @Override
    public void run() {
        while (flag > 0){
            test();
        }
    }

    public synchronized void test(){
        if (flag <= 0){
            return;
        }
        // 线程等待, 必须写在同步方法或同步代码块里
        if (flag == 5){
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(flag);
        flag--;
    }
}
public class Test5 {
    public static void main(String[] args){
        new Thread(new MyThread5()).start();
    }
}

 

posted @ 2018-10-28 00:30  huanggy  阅读(323)  评论(0编辑  收藏  举报