Java多线程交替打印奇数和偶数

/**
* Created by CHG on 2017-02-22 12:27.
* 题目:2个多线程交替打印1-100内数字,其中t1线程打印奇数,t2程打印偶数
* 主要考察对多线程创建以及多线程执行顺序的应用,难点是通过对一个对象的加锁,避免多线程随机打印,用一个开关控制打印奇数还是偶数
*/

package cn.itchg;

public class ThreadTest {

    public boolean flag;

    public class JiClass implements Runnable {
        public ThreadTest t;

        public JiClass(ThreadTest t) {
            this.t = t;
        }

        @Override
        public void run() {
            int i = 1;  //本线程打印奇数,则从1开始
            while (i < 100) {
                //两个线程的锁的对象只能是同一个object
                synchronized (t) {
                    if (!t.flag) {
                        System.out.println("-----" + i);

                        i += 2;
                        t.flag = true;
                        t.notify();

                    } else {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }


    public class OuClass implements Runnable {
        public ThreadTest t;

        public OuClass(ThreadTest t) {
            this.t = t;
        }

        @Override
        public void run() {
            int i = 2;//本线程打印偶数,则从2开始
            while (i <= 100)
                //两个线程的锁的对象只能是同一个object
                synchronized (t) {
                    if (t.flag) {
                        System.out.println("-----------" + i);
                        i += 2;
                        t.flag = false;
                        t.notify();

                    } else {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
        }
    }


    public static void main(String[] args) {
        ThreadTest tt = new ThreadTest();
        JiClass jiClass = tt.new JiClass(tt);
        OuClass ouClass = tt.new OuClass(tt);
        new Thread(jiClass).start();
        new Thread(ouClass).start();
    }
}

执行结果:
—–1
———–2
—–3
———–4
—–5
———–6
—–7
———–8
—–9
———–10
—–11
———–12
—–13
———–14
—–15
———–16
—–17
———–18
—–19
———–20
—–21
———–22
—–23
———–24
—–25
———–26
—–27
———–28
—–29
———–30
—–31
———–32
—–33
———–34
—–35
———–36
—–37
———–38
—–39
———–40
—–41
———–42
—–43
———–44
—–45
———–46
—–47
———–48
—–49
———–50
—–51
———–52
—–53
———–54
—–55
———–56
—–57
———–58
—–59
———–60
—–61
———–62
—–63
———–64
—–65
———–66
—–67
———–68
—–69
———–70
—–71
———–72
—–73
———–74
—–75
———–76
—–77
———–78
—–79
———–80
—–81
———–82
—–83
———–84
—–85
———–86
—–87
———–88
—–89
———–90
—–91
———–92
—–93
———–94
—–95
———–96
—–97
———–98
—–99
———–100

Process finished with exit code 0

你可能感兴趣的:(java)