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

-一、多个线程顺序循环打印递增的自然数,例如 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();
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mind_programmonkey

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值