多線程--交替打印100以內的奇偶數

public class test {

        //定義打印的方法
        public synchronized void print(String str){
            notify();
            System.out.println(str);
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //定義打印奇數的線程類
        class odd implements Runnable{
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for(int i=1;i<100;i+=2){
                    print("o"+i);
                }
            }
        }
        //定義打印偶數的線程類
        class even implements Runnable{
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for(int i=2;i<=100;i+=2){
                    print("e"+i);
                }
            }
        }

        public static void main(String[] args) {
            test p = new test();
            odd o = p.new odd();
            even e = p.new even();
            new Thread(o).start();
            new Thread(e).start();
        }
    }

結果:

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