多线程顺序执行

public class A1b2c3 {

    public String[] abc = {"a","b","c","d","e"};
    
    private int type = 1;
    
    /**
     * 为什么需要synchronized
     * @param index
     * @throws InterruptedException
     */
    public synchronized void printWord(int index) throws InterruptedException {
        if(type!=1) {
            wait();
        }
        
        if(index<abc.length) {
            System.out.print(abc[index]);
        }else {
            System.out.print("invalid data:" + type + "," + index);
        }
        type = 2;
        notifyAll();
    }
    
    public synchronized void printNum(int index) throws InterruptedException {
        if(type!=2) {
            wait();
        }
        
        System.out.print(index+1);
        type = 1;
        notifyAll();
    }
    
}
public class TestThread {

    public static void main(String[] args) {
        final A1b2c3 a1b2c3 = new A1b2c3();
        
        Thread thread1 = new Thread(new  Runnable() {
            public void run() {
                for(int i=0; i<a1b2c3.abc.length; i++) {
                    try {
                        a1b2c3.printWord(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread1.start();
        
        Thread thread2 = new Thread(new  Runnable() {
            public void run() {
                for(int i=0; i<a1b2c3.abc.length; i++) {
                    try {
                        a1b2c3.printNum(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread2.start();
        
    }
    
}

 

posted @ 2018-05-27 21:39  wbinbin  阅读(177)  评论(0)    收藏  举报