通过一个有趣的例子说明线程的工作机制

public class ThreadTestDemo {
	
	private int threadNum;//当前线程
	private int num;//输出的数字
	public ThreadTestDemo(int threadNum, int num) {
		super();
		this.threadNum = threadNum;
		this.num = num;
	}
	//内部线程类
	static class PrintThread extends Thread{

		private int mThreadNum;//线程数
		private ThreadTestDemo demo;//当前所在的类
		
		public PrintThread(int threadNum,ThreadTestDemo demo) {
			this.mThreadNum = threadNum;
			this.demo = demo;
		}
		
		@Override
		public void run() {
			System.out.println("当前线程是:"+ mThreadNum);
			//为demo上锁,每次只能有一个线程执行,这是关键
			synchronized (demo) {
				for(int i = 1;i<= 3;i++){
					while(true){
						System.out.println("Thread"+mThreadNum+"*****");
						//如果当前线程是demo中将要运行的线程,则跳出循环,否则说明其他线程正在运行,资源被占用,demo等待
						if(mThreadNum == demo.threadNum){
							System.out.println("Thread "+mThreadNum+" is running");
							break;
						}else{
							try {
								demo.wait();
								System.out.println("demo-thread "+demo.threadNum+" is waiting");
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
					//当前线程抢到资源后,执行循环操作
					for(int j= 1;j<=5;j++){
						System.out.println("Thread"+mThreadNum+":"+(++demo.num));
					}
					//赋予demo即将要执行的thread,并通知demo
					demo.threadNum = demo.threadNum%3+1;
					demo.notifyAll();
				}
			}
		}
		
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值