5个线程依次打印1A2B3C4D5E1F2G...

问题要求:
1.使用5个线程
2.五个线程依次打印1A2B…,即第一个线程负责打印1(A、F)等等。

解决思路:
1.轮询count ,当count满足当前线程的打印条件后,打印
2.采用wait和notifyAll进行通信

相关方法:
1.wait()方法的作用是将当前运行的线程挂起(即让其进入阻塞状态),直到notify或notifyAll方法来唤醒线程.
2.notify和notifyAll的区别在于前者只能唤醒monitor上的一个线程,对其他线程没有影响,而notifyAll则唤醒所有的线程

实验代码:

public class PrintLettersInorder {
    static Object object = new Object();
    static int count = 0 ;

    static class MyPrintThread extends Thread{
        int index ;
        public MyPrintThread(int index){
            this.index = index;
        }

        @Override
        public void run() {
            synchronized (object){
                while (count < 26){
                   try{
                       //满足打印条件后,打印并将count+1,然后唤醒其他线程,不满足条件则挂起
                       if (count%5 == (index-1)){
                           char c = (char) ('A' + count) ;
                           System.out.println(index+""+c);
                           count++ ;
                           object.notifyAll();//唤醒其他线程
                       }
                       //不满足条件,挂起
                       object.wait();
                   }catch (InterruptedException ex){
                       ex.printStackTrace();
                   }
                }
            }
        }
    }
    public static void main(String[] args) {
        Thread thread1 = new MyPrintThread(1);
        Thread thread2 = new MyPrintThread(2);
        Thread thread3 = new MyPrintThread(3);
        Thread thread4 = new MyPrintThread(4);
        Thread thread5 = new MyPrintThread(5);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        while (count < 26);
        System.exit(0);
    }
}

实验结果:

1A
2B
3C
4D
5E
1F
2G
3H
4I
5J
1K
2L
3M
4N
5O
1P
2Q
3R
4S
5T
1U
2V
3W
4X
5Y
1Z

存在一个问题,线程没有结束,于是在主线程里面加了 如下代码:

while (count < 26);
System.exit(0);
使得26个字母打印完后程序结束

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值