题目(一)

本文通过两个示例详细介绍了线程控制技术及生产者消费者模式的应用。首先展示了如何利用线程同步机制实现线程间的有序交替执行,其次实现了生产者消费者模型并确保生产和消费过程的顺畅进行。

1.

 问题:启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推,
        直到打印到75.  程序的输出结果应该为:

        线程1: 1
        线程1: 2
        线程1: 3
        线程1: 4
        线程1: 5

        线程2: 6
        线程2: 7
        线程2: 8
        线程2: 9
        线程2: 10

        ...

        线程3: 71
        线程3: 72
        线程3: 73
        线程3: 74
        线程3: 75

public class Print {
    /*
        问题:启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推,
        直到打印到75.  程序的输出结果应该为:

        线程1: 1
        线程1: 2
        线程1: 3
        线程1: 4
        线程1: 5

        线程2: 6
        线程2: 7
        线程2: 8
        线程2: 9
        线程2: 10

        ...

        线程3: 71
        线程3: 72
        线程3: 73
        线程3: 74
        线程3: 75
    */


    public static void main(String[] args) {
        Object o = new Object();

        new Thread(new PrintRunnable(o, 1)).start();
        new Thread(new PrintRunnable(o, 2)).start();
        new Thread(new PrintRunnable(o, 3)).start();
    }

}

class PrintRunnable implements Runnable {
    private final Object o;
    private int threadId;
    private static volatile int num = 1;

    PrintRunnable(Object o, int threadId) {
        this.o = o;
        this.threadId = threadId;
    }

    @Override
    public void run() {
        while (num < 65) {
            synchronized (o) {
                while (num / 5 % 3 + 1 != threadId) {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print("线程" + threadId + ": ");
                for (int i = 0; i < 5; i++) {
                    System.out.print(num + ",");
                    num++;
                }
                System.out.println();

                o.notifyAll();
            }
        }
    }
}

2.

 问题:生产者消费者模型,是互联网应用模型中比较经典的模型。
 要求实现这一模型,并实例化3个生产者和3个消费者,保证在不主动停止程序的前提下,生产和消费能够一直进行
(即当消费者无商品可消费的时候,等待生产者生产;生产者到达生产上限时候,停止生产),注意考虑线程安全。编程语言不限。

public class ShareDataV1 {
    private static final int MAX_CAPACITY = 10; //阻塞队列容量
    private static BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(MAX_CAPACITY); //阻塞队列
    private volatile boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();

    public void produce() throws InterruptedException {
        while (true) {
            boolean retvalue = blockingQueue.offer(atomicInteger.incrementAndGet(), 2, TimeUnit.SECONDS);
            if (retvalue == true) {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列" + atomicInteger.get() + "成功" + "资源队列大小= " + blockingQueue.size());
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列" + atomicInteger.get() + "失败" + "资源队列大小= " + blockingQueue.size());

            }
            TimeUnit.SECONDS.sleep(1);
        }
    }

    public void consume() throws InterruptedException {
        Integer result = null;
        while (true) {
            result = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (null == result) {
                Thread.sleep(5000);
            }
            System.out.println(Thread.currentThread().getName() + "\t 消费" + result + "成功" + "\t\t" + "资源队列大小= " + blockingQueue.size());
            Thread.sleep(1500);
        }

    }


    public static void main(String[] args) {
        ShareDataV1 v1 = new ShareDataV1();
        new Thread(() -> {
            try {
                v1.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();

        new Thread(() -> {
            try {
                v1.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "AA").start();

        new Thread(() -> {
            try {
                v1.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "AAA").start();

        new Thread(() -> {
            try {
                v1.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        new Thread(() -> {
            try {
                v1.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "BB").start();

        new Thread(() -> {
            try {
                v1.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "BBB").start();

    }
}

另外一种:


public class ShareDataV2 {

    public static AtomicInteger atomicInteger = new AtomicInteger();
    public volatile boolean flag = true;
    public static final int MAX_COUNT = 10;
    public static final List<Integer> pool = new ArrayList<>();

    public void produce() {
        // 判断,干活,通知
        while (flag) {
            // 每隔 10 毫秒生产一个商品
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            synchronized (pool) {
                //池子满了,生产者停止生产
                while (pool.size() == MAX_COUNT) {
                    try {
                        System.out.println("pool is full, wating...");
                        pool.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //干活
                pool.add(atomicInteger.incrementAndGet());
                System.out.println("produce number:" + atomicInteger.get() + "\t" + "current size:" + pool.size());
                //通知
                pool.notifyAll();
            }
        }
    }

    public void consumue() {
        // 判断,干活,通知
        while (flag) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            synchronized (pool) {
                //池子满了,生产者停止生产
                while (pool.size() == 0) {
                    try {
                        System.out.println("pool is empty, wating...");
                        pool.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //干活
                int temp = pool.get(0);
                pool.remove(0);
                System.out.println("cousume number:" + temp + "\t" + "current size:" + pool.size());
                //通知
                pool.notifyAll();
            }
        }
    }

    public void stop() {
        flag = false;
    }

    public static void main(String[] args) {
        ShareDataV2 shareDataV2 = new ShareDataV2();
        new Thread(() -> {
            shareDataV2.produce();
        }, "AAA").start();

        new Thread(() -> {
            shareDataV2.consumue();
        }, "BBB").start();

        new Thread(() -> {
            shareDataV2.produce();
        }, "AA").start();

        new Thread(() -> {
            shareDataV2.consumue();
        }, "BB").start();

        new Thread(() -> {
            shareDataV2.produce();
        }, "A").start();

        new Thread(() -> {
            shareDataV2.consumue();
        }, "B").start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值