欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Leetcode_多线程】- 三个线程循环打印自然数

程序员文章站 2022-05-28 18:02:33
...

-一、多个线程顺序循环打印递增的自然数,例如 3 个线程:t-0,t-1,t-2,程序输出如下:
t-0 0
t-1 1
t-2 2
t-0 3
t-1 4
t-2 5

package com.lcz.thread;

import java.util.concurrent.Semaphore;

// 类
class Num{
	// 自然数
	int i = 0;
	int n;


	// 初始化
	public  Num(int n) {
		this.n = n;
	}
	// 依次打印
	Semaphore s0 = new Semaphore(1);
	Semaphore s1 = new Semaphore(0);
	Semaphore s2 = new Semaphore(0);
	// 第一个线程打印的方法
	public void print0() throws InterruptedException {
		for(int i=0;i<n;i+=3) {
			s0.acquire();
			System.out.println(Thread.currentThread().getName() + " "+ i);
			s1.release();
		}
	}
	
	// 第二个线程打印方法
	public void print_2() throws InterruptedException {
		for(int i=1;i<n;i+=3) {
			s1.acquire();
			System.out.println(Thread.currentThread().getName()+ " " + i);
			s2.release();
		}

	}
	
	// 第三个线程打印方法
	public void print_3() throws InterruptedException {
		for(int i=2;i<n;i+=3) {
			s2.acquire();
			System.out.println(Thread.currentThread().getName()+ " " + i);
			s0.release();
		}

	}
}
public class Test25 {
	public static void main(String[] args) {
		Num num = new Num(10);
		// 线程
		Thread t0 = new Thread(()->{
			try {
				num.print0();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		},"t0");
		
		Thread t1 = new Thread(()->{
			try {
				num.print_2();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		},"t1");
		
		Thread t2 = new Thread(()->{
			try {
				num.print_3();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		},"t2");
		
		t0.start();
		t1.start();
		t2.start();
	}
}