多線程面試題——交替打印1和2

public class Multi {
    public static void main(String[] args) throws Exception {
        final Object obj = new Object();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        synchronized (obj) {
                            obj.notifyAll();
                            obj.wait();
                            System.out.println(1);
                        }
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        synchronized (obj) {
                            obj.notifyAll();
                            obj.wait();
                            System.out.println(2);
                        }
                    }
                } catch (Exception e) {

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