线程顺序输出

参考:https://blog.csdn.net/qq_41384351/article/details/91447089

三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示

 

ThreadTest.java

package jvm;

/*
 * 三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示
 * */
public class ThreadTest {

    
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 ThreadName threadName = new ThreadName();
	        threadName.setIndex(0);
	        Thread thread0 = new Thread(new ThreadDemo(0, threadName));
	        Thread thread1 = new Thread(new ThreadDemo(1,threadName));
	        Thread thread2 = new Thread(new ThreadDemo(2,threadName));
	        thread0.setName("A");
	        thread1.setName("B");
	        thread2.setName("C");
	        thread0.start();
	        thread1.start();
	        thread2.start();
	}
}

 

ThreadName.java

package jvm;

public class ThreadName {
	private int index;//当前执行线程ID

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}
}

ThreadDemo.java

package jvm;

public class ThreadDemo extends Thread {

	private int threadNum;// 当前线程编号
	private ThreadName threadName;// 线程间传递对象

	public ThreadDemo(int threadNum, ThreadName threadName) {
		this.threadName = threadName;
		this.threadNum = threadNum;
	}

	@Override
	public void run() {
		int i = 1;
		while (i <= 10) {
			synchronized (threadName) {
				while (threadNum != threadName.getIndex()) {
					try {
						threadName.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.print(Thread.currentThread().getName());
				threadName.setIndex((threadNum + 1) % 3);
				threadName.notifyAll();
				i++;
			}
		}

	}

}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值