ITeye博客

synchronized (this) 柳暗花明又一村

tojaoomy · 2013-05-17 16:23 · Java · Thread · 编程语言 · Markdown

今天写一个测试类,主要是测试wait(long timeout)到底会不会自动notify,到后来发现

一些很诡异的东西。

package com.hp.thread.chapter04;

public class WaitAndNotify {
	private Object obj = new Object();
	public static void testPureWait(){
		new Thread(new Runnable(){
			public void run() {
				synchronized (this) {
					try {
						System.out.println("thread 0");
						wait();
						System.out.println("thread 0 waited...");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				synchronized (this) {
					try {
						System.out.println("thread 1");
						wait(1000);
						System.out.println("thread 1 waited...");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	public void testWait1000(){
		new Thread(new Runnable(){
			public void run() {
				System.out.println("thread 0 " + this);
				synchronized (obj) {
					while(true){
						try {
							System.out.println("thread 0 running...");
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				System.out.println("thread 1 " + this);
				synchronized (obj) {
					try {
						while(true){
							wait(1000);
							System.out.println("thread 1 waited...");
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	//通过打印出来的this,发现2个是不同的结果,为什么呢?
	//因为this是指向当前对象的引用,不过方法中都是new Thread(new Runnable(){}).start()
	//方式来生成,都是通过匿名的方式,所以每次的this都是指向new Thread()的WaitAndNotify对象
	public void testWait1000_2(){
		new Thread(new Runnable(){
			public void run() {
				synchronized (this) {
					while(true){
						try {
							System.out.println("thread 0");
							System.out.println("thread 0 running...");
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				synchronized (this) {
					try {
						while(true){
							System.out.println("thread 1");
							wait(1000);
							System.out.println("thread 1 waited...");
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	public static void testWait(){
		new Thread(new Runnable(){
			public void run() {
				while(true){
					synchronized (this) {
						try {
							System.out.println("...");
							wait();
							System.out.println("waited...");
							notifyAll();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}).start();
		
		new Thread(new Runnable(){
			public void run() {
				while(true){
					synchronized (this) {
						try {
							notifyAll();
							System.out.println("notify...");
							wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}).start();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		testPureWait();
//		testWait();
		new WaitAndNotify().testWait1000();
	}

}

 调用testWait1000_2方法得到的结果不是我期望(线程0始终在运行,线程1是不会运行的),但世界的结果恰恰相反,好事2个线程不相干,测试结果如下

thread 0
thread 0 running...
thread 1
thread 1 waited...
thread 0
thread 0 running...
thread 1
thread 0
thread 0 running...
thread 1 waited...
thread 1

 但是运行testWait1000正好是我要的结果,开始百思不得其解,后来打印this发现mystery了

thread 0 com.hp.thread.chapter04.WaitAndNotify$3@525483cd
thread 0 running...
thread 1 com.hp.thread.chapter04.WaitAndNotify$4@67f1fba0
thread 0 running...
thread 0 running...
thread 0 running...
thread 0 running...

 发现2个this的地址完全不一样,细想一下豁然开朗。

评论(7)

  1. #7 楼 · tojaoomy · 2013-05-20 13:54

    teasp writes:

    [quote=tojaoomy][quote=teasp][quote=tojaoomy][quote=teasp]匿名类的this当然是指向匿名类对象自身了。我好奇的是你为什么要“测试wait(long timeout)到底会不会自动notify”。测试的结果是什么呢?[/quote] 结果是会notify[/quote] 如果我告诉你你的结果是错误的呢?[/quote] 错误的?不解,那就麻烦你说一下原因? 这是我的理解,timeout时间一过,该线程立马notify,不过会等待 对象锁,不是waiting状态了,而是等待锁的状态。[/quote] 这是当然的啊,还用测试吗?我以为你测的是时间还没到,wait的线程就自己醒了呢。

    呵呵,理论终归是理论,还是要实践的。 而我测试的目的是notify后的reaction是什么罢了。

  2. #6 楼 · teasp · 2013-05-20 12:37

    tojaoomy writes:

    [quote=teasp][quote=tojaoomy][quote=teasp]匿名类的this当然是指向匿名类对象自身了。我好奇的是你为什么要“测试wait(long timeout)到底会不会自动notify”。测试的结果是什么呢?[/quote] 结果是会notify[/quote] 如果我告诉你你的结果是错误的呢?[/quote] 错误的?不解,那就麻烦你说一下原因? 这是我的理解,timeout时间一过,该线程立马notify,不过会等待 对象锁,不是waiting状态了,而是等待锁的状态。

    这是当然的啊,还用测试吗?我以为你测的是时间还没到,wait的线程就自己醒了呢。

  3. #5 楼 · tojaoomy · 2013-05-20 10:30

    teasp writes:

    [quote=tojaoomy][quote=teasp]匿名类的this当然是指向匿名类对象自身了。我好奇的是你为什么要“测试wait(long timeout)到底会不会自动notify”。测试的结果是什么呢?[/quote] 结果是会notify[/quote] 如果我告诉你你的结果是错误的呢?

    错误的?不解,那就麻烦你说一下原因? 这是我的理解,timeout时间一过,该线程立马notify,不过会等待 对象锁,不是waiting状态了,而是等待锁的状态。

  4. #4 楼 · teasp · 2013-05-20 08:24

    tojaoomy writes:

    [quote=teasp]匿名类的this当然是指向匿名类对象自身了。我好奇的是你为什么要“测试wait(long timeout)到底会不会自动notify”。测试的结果是什么呢?[/quote] 结果是会notify

    如果我告诉你你的结果是错误的呢?

  5. #3 楼 · tojaoomy · 2013-05-19 21:58
    
    package com.hp.thread;
    
    import java.util.Random;
    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class CyclicBarrierTest {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		CyclicBarrier barrier = new CyclicBarrier(3,new Runnable() {
    			
    			@Override
    			public void run() {
    				System.out.println("get together");
    			}
    		});
    		ExecutorService executor = Executors.newFixedThreadPool(3);
    		executor.submit(new Thread(new Runner(barrier, "1号选手")));
            executor.submit(new Thread(new Runner(barrier, "2号选手")));
            executor.submit(new Thread(new Runner(barrier, "3号选手")));
            executor.shutdown();
    
    	}
    
    }
    
    class Runner implements Runnable{
    	private CyclicBarrier barrier;
    	private String name;
    	
    	public Runner(CyclicBarrier barrier,String name) {
    		this.barrier = barrier;
    		this.name = name;
    	}
    	@Override
    	public void run() {
    		try {
    			Thread.sleep(1000*(new Random().nextInt(2)));
    			System.out.println( name + " ready...");
    			barrier.await();
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		} catch (BrokenBarrierException e) {
    			e.printStackTrace();
    		}
    		System.out.println(name + "go!");
    	}
    	
    }
    
    
  6. #2 楼 · tojaoomy · 2013-05-19 21:49

    teasp writes:

    匿名类的this当然是指向匿名类对象自身了。我好奇的是你为什么要“测试wait(long timeout)到底会不会自动notify”。测试的结果是什么呢?

    结果是会notify

  7. #1 楼 · teasp · 2013-05-17 18:20

    匿名类的this当然是指向匿名类对象自身了。我好奇的是你为什么要“测试wait(long timeout)到底会不会自动notify”。测试的结果是什么呢?

评论功能维护中,当前仅展示历史评论。