【操作系统】利用信号量多个线程轮流打印数字

一、运行效果

  先看效果:
【操作系统】利用信号量多个线程轮流打印数字_第1张图片
  传参3和10,那就是3个线程轮流打印10~1 。如下:
【操作系统】利用信号量多个线程轮流打印数字_第2张图片
  我们不妨胆子放开点。114个线程轮流打印514~1 。像这样传参。
【操作系统】利用信号量多个线程轮流打印数字_第3张图片
  运行效果:
【操作系统】利用信号量多个线程轮流打印数字_第4张图片

二、代码实现

  这个其实都算很简单了。我之前写过一个复杂得多的,传参一个代表有向图的矩阵,让线程按照有向图中的前驱关系依次运行。链接在这里:【操作系统&数据结构图论】用有向图临接矩阵获得满足该前驱关系的线程数组

  这个算法其实也是传参了一个图,一个环形的图,或者说一个环形单链表,即第n个节点只有指向第n+1个节点的指针。线程的调度需要满足这个顺序。

  理清思路其实就好写多了。

import java.util.concurrent.Semaphore;

public class ThreadTest {

	static int x = 10;

	public static void func(int num, int n) {

		ThreadTest.x = n;

		Semaphore[] semaphores = new Semaphore[num];
		Thread[] threads = new Thread[num];

		for (int i = 0; i < num; i++) {
			semaphores[i] = new Semaphore(1);
		}

		for (int i = 1; i < num; i++) {
			try {
				semaphores[i].acquire();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < num; i++) {

			int j = i;

			threads[i] = new Thread(() -> {
				while (true) {
					try {
						semaphores[j].acquire();
						if (x > 0) {
							System.out.println(Thread.currentThread().getName() + ": " + x--);
						} else {
							semaphores[(j + 1) % num].release();
							break;
						}
						semaphores[(j + 1) % num].release();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});

			threads[i].start();

		}

	}

	public static void main(String[] args) {
		func(114, 514);
	}

}

你可能感兴趣的:(操作系统,算法,java,操作系统)