多线程并发问题(通过sleep突显出来)

package com.cyj.thread.manage;


/**
 * 
 * 并发问题:
 * sleep延时1秒后
 * 三个代理共享一个资源地问题显示出来
 * 不能精确控制多少次,并且终止的时间不规范
 * 每秒运行多少次没有办法控制,本机实验有一次两次三次
 * 共运行不到150次
 * @author Chyjrily
 *
 */
public class NetworkDalay {

	public static void main(String[] args) {
		//真实角色
		Cuiyongyuan cyy = new Cuiyongyuan();
		
		//代理角色
		Thread c1 = new Thread(cyy,"一号支持者");
		Thread c2 = new Thread(cyy,"二号支持者");
		Thread c3 = new Thread(cyy,"三号支持者");
		
		//启动线程
		c1.start();
		c2.start();
		c3.start();
	}
	        
}

class Cuiyongyuan implements Runnable{
	private int num = 0;
	
	public void run() {
		while(true) {
			if(num>=50) {
				break;
			}
			
			try {
				Thread.sleep(1000); //加了延时之后,数据可能不准确
			} catch (InterruptedException e) {  //不能对外声明异常
				e.printStackTrace();
				System.out.println("延时失败 ");
			}
			
			num += 1;
			if(num%2 == 0) {
			    System.out.println(Thread.currentThread().getName() + "评论支持了崔永元一下"+"共评论"+num+"次");
			}else {
				System.out.println(Thread.currentThread().getName() + "评论损了冯裤子一下"+"共评论"+num+"次" );
			}
			
		}
	}	
}

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/81068177
今日推荐