testthread3.java.bak

来自「文件输入流」· BAK 代码 · 共 47 行

BAK
47
字号
class MyThread implements Runnable{

	volatile private int share;
	volatile private Integer it;
	public MyThread(int _share){
		this.share=_share;
		it=new Integer(share);
	}
	
	/**
			synchronized 代码块:监视器就是指定的对象
	*/
	public void run() {

		while(true){
			synchronized(it){ 
				
				if (share > 0) {
					try{
							Thread.sleep(200);	
					}
					catch(Exception e){
							System.out.println("捕获到异常");	
					}
					share--;
					System.out.println(Thread.currentThread().getName()+"  share = " + share);
				} else {
					System.out.println(Thread.currentThread().getName()+"  share <= 0");
					break;
				}
			}
		}
	}

}
public class TestThread3 {
	public static void main(String[] args) {
		MyThread mt=new MyThread(20);
		Thread t1=new Thread(mt);
		Thread t2=new Thread(mt);
		Thread t3=new Thread(mt);
		t3.start();
		t1.start();
		t2.start();
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?