通过 N 个线程顺序循环打印从 0 至 100

using System;
using System.Threading;

class PrintThread
{
    private int id;
    private int totalThreads;
    private int startNum;
    private int endNum;
    private ManualResetEvent waitEvent;

    public PrintThread(int id, int totalThreads, int startNum, int endNum, ManualResetEvent waitEvent)
    {
        this.id = id;
        this.totalThreads = totalThreads;
        this.startNum = startNum;
        this.endNum = endNum;
        this.waitEvent = waitEvent;
    }

    public void Run()
    {
        for (int i = startNum; i <= endNum; i += totalThreads)
        {
            Console.WriteLine("Thread {0}: {1}", id, i);
            Thread.Sleep(100);
        }

        waitEvent.Set();  // 通知主线程该线程已完成打印任务
    }
}

class Program
{
    static void Main(string[] args)
    {
        int n = 3;  // N 个线程
        int totalNums = 101;  // 打印从 0 至 100
        ManualResetEvent[] events = new ManualResetEvent[n];

        for (int i = 0; i < n; i++)
        {
            events[i] = new ManualResetEvent(false);
            PrintThread thread = new PrintThread(i, n, i, totalNums - 1, events[i]);
            Thread t = new Thread(thread.Run);
            t.Start();
        }

        // 等待所有线程完成打印任务
        WaitHandle.WaitAll(events);

        Console.WriteLine("All threads have finished printing.");
    }
}

这段代码中,我们创建了 N 个线程,每个线程负责打印从 0 至 100 中特定的一部分数字。在每个线程的Run方法中,我们使用步长为 N 的方式遍历该线程负责的数字,并输出该数字。为了模拟真实的场景,我们在输出数字之后让线程休眠 100 毫秒。

在主程序中,我们创建了 N 个PrintThread对象,并分别给它们分配不同的数字范围。然后,我们启动这 N 个线程,并使用WaitHandle.WaitAll方法等待它们完成打印任务。最终输出的结果是从 0 至 100 的数字,按顺序依次被打印出来。

public class PrintThread implements Runnable {
    private int threadId;
    private int threadNum;
    private int count;
    private Object lock;

    public PrintThread(int threadId, int threadNum, int count, Object lock) {
        this.threadId = threadId;
        this.threadNum = threadNum;
        this.count = count;
        this.lock = lock;
    }

    public void run() {
        int i = 0;
        while (true) {
            synchronized (lock) {
                while (i % threadNum != threadId) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (i > count) {
                    break;
                }

                System.out.println("Thread " + threadId + ": " + i);
                i++;

                lock.notifyAll();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        int threadNum = 5;
        int count = 100;
        Object lock = new Object();

        for (int i = 0; i < threadNum; i++) {
            PrintThread thread = new PrintThread(i, threadNum, count, lock);
            new Thread(thread).start();
        }
    }
}
View Code

在这段代码中,我们创建了一个PrintThread类来表示每个线程。构造函数接收线程的 ID、线程数、计数值和锁对象。在run()方法中,我们使用synchronized关键字来确保线程之间的同步。线程会循环打印数值,当数值超过给定的计数值时,线程会退出循环。在每次打印完数值后,线程会通知所有等待该锁的线程继续执行,以便下一个线程打印数值。

在主程序中,我们创建了一个锁对象和多个PrintThread对象。然后,我们启动每个线程。在每个线程中,线程会根据它们的 ID 和线程数来计算它们需要打印的数值。在打印完数值后,线程会通知下一个线程继续执行,直到所有线程完成任务并退出。

posted @ 2023-03-29 23:42  elegydance  阅读(189)  评论(0编辑  收藏  举报