启动3个线程轮番打印递增的数字

启动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 PrintNoDemo {
    private static int printNO = 1;
    private static int printThread = 1;
    private static Condition condition1;
    private static Condition condition2;
    private static Condition condition3;

    private static ReentrantLock lock = new ReentrantLock();
    
    public static void main(String[] args){
        condition1 = lock.newCondition();
        condition2 = lock.newCondition();
        condition3 = lock.newCondition();
        
        for(int i=0; i<3; i++){
            Thread thread = new Thread(new Runnable(){

                @Override
                public void run() {
                    while(printNO <= 75){
                        printNo();
                    }
                }
            },"线程"+(i+1));
            thread.start();
        }
    }

    public static void printNo() {
        try {
            lock.lock();
            String threadName = Thread.currentThread().getName();
            //判断线程,选择等待Condition
            if(!threadName.equals("线程"+printThread)){
                if(threadName.equals("线程1")){
                    condition1.await();
                } else 
                if(threadName.equals("线程2")){
                    condition2.await();
                } else
                if(threadName.equals("线程3")){
                    condition3.await();
                }
            }
            
            //处理打印
            for (int i = 0; i < 5; i++) {
                if(printNO > 75){
                    break;
                }
                System.out.println(Thread.currentThread().getName() +":"+ printNO++);
            }
            //获取下一个打印线程
            printThread = printThread%3 +1;
            
            if(threadName.equals("线程1")){
                condition2.signal();
            }else 
            if(threadName.equals("线程2")){
                condition3.signal();
            }else 
            if(threadName.equals("线程3")){
                condition1.signal();
            }
            
//            lock.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}

网友实现方法

class NumberPrinter extends Thread {
    static int c = 0;
    static int state = 0;
    private int id;

    @Override
    public synchronized void run() {
        while (state < 15) {
            if (state % 3 == id) {
                for (int j = 0; j < 5; j++) {
                    c++;
                    System.out.format("Thread %d: %d %n", id, c);
                }
                state++;; 
            }
        }
    }

    public NumberPrinter(int id) {
        this.id = id;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new NumberPrinter(i).start();
        }
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个典型的多线程编程问题,可以使用锁和条件变量来实现。以下是一个实现该功能的 Python 代码: ```python import threading class NumberPrinter: def __init__(self): self.print_num = 1 self.lock = threading.Lock() self.cond_var = threading.Condition(self.lock) def print_numbers(self, thread_id, start_num): with self.lock: while self.print_num <= 60: if self.print_num % 5 == start_num: for i in range(5): print("Thread {}: {}".format(thread_id, self.print_num)) self.print_num += 1 self.cond_var.notify_all() else: self.cond_var.wait() if __name__ == "__main__": printer = NumberPrinter() t1 = threading.Thread(target=printer.print_numbers, args=(1, 0)) t2 = threading.Thread(target=printer.print_numbers, args=(2, 1)) t3 = threading.Thread(target=printer.print_numbers, args=(3, 2)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() ``` 其中,`NumberPrinter` 类维护了一个 `print_num` 变量表示当前需要打印数字,一个锁 `lock` 用来保证线程安全,和一个条件变量 `cond_var` 用来协调三个线程的执行。每个线程调用 `print_numbers` 方法,进入循环,如果当前需要由该线程打印数字,就打印 5 个数字,并将 `print_num` 更新为下一个需要打印数字。否则,该线程就进入等待状态,等待其他线程通知它可以开始执行。三个线程的 `start_num` 参数分别为 0,1,2,表示它们分别从 1,6,11 开始打印数字。最后三个线程使用 `join` 方法等待所有线程执行完毕。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值