题:使用生产者和消费者模式实现,交替输出:
假设只有两个线程,输出以下结果:
t1-->1
t2-->2
t1-->3
t2-->4
...
要求:交替,t1输出奇数,t2输出偶数。
package top.threadtest;

/**
 * @author dj
 * @date 2020-09-16
 */
public class AlternateOutput {
    public static void main(String[] args) {
        Printer p = new Printer();

        Thread t1 = new Thread(new MyThread1(p));
        Thread t2 = new Thread(new MyThread2(p));

        t1.setName("奇数线程");
        t2.setName("偶数线程");

        t1.start();
        t2.start();
    }
}

// 要打印的资源
class Printer {
    private int i = 1;

    public int getI() {
        return i;
    }

    public int printI() {
        return i++;
    }
}

// 输出奇数的线程,线程1
class MyThread1 implements Runnable {
    private Printer p;

    public MyThread1(Printer p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (p.getI() < 100) {
            synchronized (p) {
                if (p.getI() % 2 == 0) {
                    try {
                        p.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "---->" + p.printI());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.notifyAll();
            }
        }
    }
}

// 输出偶数的线程,线程2
class MyThread2 implements Runnable {
    private Printer p;

    public MyThread2(Printer p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (p.getI() < 100) {
            synchronized (p) {
                if (p.getI() % 2 != 0) {
                    try {
                        p.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "---->" + p.printI());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.notifyAll();
            }
        }
    }
}
分类: Java SE

Deng Jia

Keep Moving.

0 条评论

发表评论

电子邮件地址不会被公开。