JAVA 线程 sleep

class Test11{
	//主要测试Thread.sleep(100)不释放当前对象的锁,前提你要理解Thread.sleep()必然而且只能是当前线程调用的方法。
	public static void main(String args[]){
	
		class T{
		
			public synchronized void a(){
				
				try{
				  //long l = System.currentTimeMillis();
				  //System.out.println(l);
					Thread.sleep(1000);
					//wait(1000);
					/*
					while(System.currentTimeMillis()-l<1000){
						System.out.println(1);
						wait(System.currentTimeMillis()-l);
					}*/
					System.out.println("a");
				}catch(Exception e){
				}
			}
			
			public synchronized void b(){
				
				try{
					
					System.out.println("b");
				}catch(Exception e){}
			
			}
			
			public void c(){
				try{
					Thread.sleep(10000);
					System.out.println("c");
				}catch(Exception e){}
			}
			
			public void d(){
				try{
				//	Thread.sleep(10000);
					System.out.println("d");
				}catch(Exception e){}
			}
			
		}
		
		class Tt extends Thread{
		
			private T t;
			public Tt(T t){
				this.t = t;
			}
			public void run(){
				this.t.a();
			}
		}
		
		class Ttt extends Thread{
		
			private T t;
			public Ttt(T t){
				this.t = t;
			}
			public void run(){
				this.t.b();
			}
		}
		
		class Tttt extends Thread{
		
			private T t;
			public Tttt(T t){
				this.t = t;
			}
			public void run(){
				this.t.c();
			}
		}
		
		class Ttttt extends Thread{
		
			private T t;
			public Ttttt(T t){
				this.t = t;
			}
			public void run(){
				this.t.d();
			}
		}
		
		T t = new T();
		
		new Tttt(t).start();
		new Tt(t).start();
		new Ttt(t).start();
		new Ttttt(t).start();
		
		
	}
}



多个线程对象产生的多个线程,在执行同一对象的不同的同步的方法的时候,Thread.sleep(x),并不会释放相同对象的锁,而wait(x)会释放,这样可以不影响下面的线程执行其他同步的方法,在执行同一对象的不同的不同步的方法的时候,Thread.sleep(x),只阻塞当前线程,如果改成wait(x), 这本身就是有问题的,因为wait()只能在同步方法中调用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值