java wait和notify及 synchronized sleep 总结

java 中线程我一直弄不清线程锁等 所以写了一些例子验证看法:

在这之前先看下API中wait中的解释:

wait:方法来之java.lang.Objetc

方法翻译:在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。并释放所有同步锁 //当前线程必须拥有此对象监视器。 (sleep不会释放)

sleep:休眠当前线程 并且不释放同步锁

notify:唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。该方法不会释放调用线程的同步锁

synchronized:当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块


那么实验1:

大家看到线程A B C分别锁了 Test中 s1 s2 s3 

猜想:因为s1 s2 s3 不是同一对象所以会交替打印 我是线程A 线程B 线程C

package com.fmy.test;

public class Test {
	static String s1 ="";
	static String s2 ="";
	static String s3 ="";
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		C c = new C();
		c.start();
		b.start();
		a.start();
		
	}
}
class A extends Thread{

	@Override
	public void run() {
		synchronized (Test.s1) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程A");
			}
		}
	}
	
}
class B extends Thread{
	@Override
	public void run() {
		synchronized (Test.s2) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程B");
			}
		}
	}
}
class C extends Thread{
	@Override
	public void run() {
		synchronized (Test.s3) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程C");
			}
		}
	}
}
输出结果:

我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C
我是线程C

结果发现打印的是 全是 线程C

原因 S1 S2 S3指向同一常量池 所以锁的是同一内存区 所以 static String s1 =new String()  static String s2 =new String()  static String s3 =new String()  的时候他们会交替打印



那么实验2:

package com.fmy.test;

public class Test {
	static String s1 =new String();
	static String s2 =new String();
	static String s3 =new String();
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		C c = new C();
		c.start();
		b.start();
		a.start();
		
	}
}
class A extends Thread{

	@Override
	public void run() {
		synchronized (Test.s1) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程A");
			}
		}
	}
	
}
class B extends Thread{
	@Override
	public void run() {
		synchronized (Test.s2) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程B");
			}
		}
	}
}
class C extends Thread{
	@Override
	public void run() {
		synchronized (Test.s3) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程C");
			}
		}
	}
}

输出结果:

我是线程A
我是线程C
我是线程B
我是线程A
我是线程C
我是线程B
我是线程A
我是线程C
我是线程B
我是线程A
我是线程C
我是线程A
我是线程B
我是线程C
我是线程B
我是线程A

结论:证明实验一结论是正确的

实验三:

 wait是否要在synchronized方法块中?

public class Test {
	static String s1 =new String();
	static String s2 =new String();
	static String s3 =new String();
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		C c = new C();
		a.start();
		
	}
}
class A extends Thread{

	@Override
	public void run() {
//		synchronized (Test.s1) {
			while (true) {
				try {
					Test.s1.wait();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程A");
			}
//		}
	}

输出结果:异常

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.fmy.test.A.run(Test.java:22)


结论: wait是要在synchronized方法块中

实验四: notify是否要在synchronized方法块中

与实验三差不多 所以不贴出代码

结果:notify是否要在synchronized方法块中

实验五: 某个线程没有X的对象锁调用 X.WAIT() 是否会让该对象阻塞 或者其他拥有 X对象锁的线程阻塞

    package com.fmy.test;

public class Test {
    static String s1 =new String();
    static String s2 =new String();
    static String s3 =new String();
    static String s4 =new String();
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        a.start();
        b.start();
        
    }
}
class A extends Thread{

    @Override
    public void run() {
        synchronized (Test.s4) {
            while (true) {
                try {
                    Test.s2.wait();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("我是线程A");
            }
        }
    }
    
}
class B extends Thread{
    @Override
    public void run() {
        synchronized (Test.s2) {
            while (true) {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("我是线程B");
            }
        }
    }
}

输出结果:java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.fmy.test.A.run(Test.java:24)
java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.fmy.test.A.run(Test.java:24)
我是线程A
我是线程B
我是线程B
我是线程A
java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.fmy.test.A.run(Test.java:24)
我是线程A
我是线程B
我是线程B
我是线程A


结论:不能锁住当前线程和其他拥有该对象锁的线程并且会报异常 所以:当你想阻塞某个线程的时候请在某个线程中调用wait方法 并且对象拥有该锁

实验六: 某个线程没有X对象锁调用notify()可以唤醒其他被锁的对象吗?

package com.fmy.test;

public class Test {
    static String s1 =new String();
    static String s2 =new String();
    static String s3 =new String();
    static String s4 =new String();
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        a.start();
        b.start();
        
    }
}
class A extends Thread{

    @Override
    public void run() {
        synchronized (Test.s4) {
            while (true) {
                try {
                    sleep(1000);
                    Test.s2.notify();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("我是线程A");
            }
        }
    }
    
}
class B extends Thread{
    @Override
    public void run() {
        synchronized (Test.s2) {
            try {
                Test.s2.wait();
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            while (true) {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("我是线程B");
            }
        }
    }
}


输出结果:java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at com.fmy.test.A.run(Test.java:25)
我是线程A
java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at com.fmy.test.A.run(Test.java:25)
我是线程A
java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at com.fmy.test.A.run(Test.java:25)
我是线程A

结论:一个对象没有X的对象锁使用了notify将不会唤醒其他线程使用了X.wait导致的阻塞


实验七:wait会是释放线所有该线程占有的锁吗?

<pre name="code" class="java">package com.fmy.test;

public class Test {
	static String s1 =new String();
	static String s2 =new String();
	static String s3 =new String();
	static String s4 =new String();
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		C c = new C();
		a.start();
		b.start();
		
	}
}
class A extends Thread{

	@Override
	public void run() {
		synchronized (Test.s2) {
			synchronized (Test.s1) {
				while (true) {
					try {
						System.out.println("我是A让自己阻塞");
						Test.s2.wait();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("我是线程A");
				}
			}
			
		}
	}
	
}
class B extends Thread{
	@Override
	public void run() {
		synchronized (Test.s2) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程B");
			}
		}
	}
}





输出结果:我是A让自己阻塞
我是线程B
我是线程B
我是线程B
我是线程B

结论:wait方法会释放线程的所有同步锁

实验八:sleep会是释放线所有该线程占有的锁吗?

package com.fmy.test;

public class Test {
	static String s1 =new String();
	static String s2 =new String();
	static String s3 =new String();
	static String s4 =new String();
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		C c = new C();
		a.start();
		b.start();
		
	}
}
class A extends Thread{

	@Override
	public void run() {
		synchronized (Test.s2) {
			synchronized (Test.s1) {
				while (true) {
					try {
						System.out.println("我是A让自己睡一下");
						sleep(1000);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("我是线程A");
				}
			}
			
		}
	}
	
}
class B extends Thread{
	@Override
	public void run() {
		synchronized (Test.s2) {
			while (true) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("我是线程B");
			}
		}
	}
}



输出结果:我是A让自己睡一下
我是线程A
我是A让自己睡一下
我是线程A
我是A让自己睡一下
我是线程A
我是A让自己睡一下

结论:sleep方法不会释放调用线程的同步锁

实验九:证明 和理解   notify():该方法不会释放调用线程的同步锁,只是会唤醒被wait()阻塞的线程


<span style="color:#000000;">package com.fmy.test;

public class Test {
	static String s1 =new String();
	static String s2 =new String();
	static String s3 =new String();
	static String s4 =new String();
	 static A a = null;
	
	public static void main(String[] args) {
		a  = new A();
		B b = new B();
		C c = new C();
		a .start();
		b.start();
		
	}
}
class A extends Thread{

	@Override
	public void run() {
		
		synchronized (Test.s1) {
			System.out.println("我是A让自己阻塞");
			try {
				Test.s1.wait();
			} catch (InterruptedException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
				while (true) {
					
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("我是线程A");
				}
			
			
		}
	}
	
}
class B extends Thread{
	@Override
	public void run() {
		synchronized (Test.s1) {
			while (true) {
				try {
					sleep(1000);//保证线程A先执行 到wait处
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("被阻塞后的A线程状态"+Test.a.getState());
				System.out.println("我是线程B");
				//唤醒A线程
				Test.s1.notify();
				System.out.println("被唤醒线程A的状态"+Test.a.getState());
			}
		}
	}
}</span>


输出结果:我是A让自己阻塞
被阻塞后的A线程状态WAITING
我是线程B
被唤醒线程A的状态BLOCKED
被阻塞后的A线程状态BLOCKED
我是线程B
被唤醒线程A的状态BLOCKED
被阻塞后的A线程状态BLOCKED
我是线程B


结论:证实实验九。直到调用notify的线程结束或者自行放弃同步锁才能到被唤醒的线程执行。notify方法只会唤醒被阻塞的线程而已 并不会影响到调用此方法的线程所有状态和锁











原文地址:https://www.cnblogs.com/muyuge/p/6152327.html