【发布时间】:2017-08-11 03:04:52
【问题描述】:
每当调用并返回 Object 类中的 wait、notify 和 notifyAll 方法时,我都会尝试打印到控制台。为此,我创建了一个包装类,它代表锁定对象调用 wait、notify 和 notifyAll 方法。然后我使用包装器上的方法而不是等待、通知和 notifyAll。这是我最好的尝试,
线程一运行 Runnable r1
Runnable r1 = new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
// wait not wrapped in while loop for brevity.
//lock.wait();
lock.objWrapper.waitNew(); // Use the wrapper method instead of wait()
} catch (InterruptedException e) {}
}
}
};
线程两个运行 Runnable r2
Runnable r2 = new Runnable() {
@Override
public void run() {
synchronized(lock) {
//lock.notifyAll();
lock.objWrapper.notifyAllNew(); // Use the wrapper method instead of notifyAll()
}
}
};
Lock 类定义为,
public class Lock {
ObjWrapper objWrapper = new ObjWrapper(this);
// shared data here
}
Lock lock = new Lock();
包装类定义为,
public class ObjWrapper {
Object obj = null;
ObjWrapper(Object obj) {
System.out.println("New Object wrapper created: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
this.obj = obj;
}
public void waitNew() throws InterruptedException {
System.out.println("Entering Object::wait: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
obj.wait();
System.out.println("Exiting Object::wait: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
}
public void notifyNew() {
System.out.println("Entering Object::notify: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
obj.notify();
System.out.println("Exiting Object::notify: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
}
public void notifyAllNew() {
System.out.println("Entering Object::notifyAll: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
obj.notifyAll();
System.out.println("Exiting Object::notifyAll: Thread: " + Thread.currentThread() + " at time: " + Instant.now());
}
}
最后,启动线程使用,
Thread t1 = new Thread(r1);
t1.setName("Thread One");
t1.start();
Thread t2 = new Thread(r2);
t2.setName("Thread Two");
t2.start();
控制台输出,
New Object wrapper created: Thread: Thread[main,5,main] at time: 2017-03-19T22:48:28.771Z
Entering Object::wait: Thread: Thread[Thread One,5,main] at time: 2017-03-19T22:48:28.844Z
Entering Object::notifyAll: Thread: Thread[Thread Two,5,main] at time: 2017-03-19T22:48:31.845Z
Exiting Object::notifyAll: Thread: Thread[Thread Two,5,main] at time: 2017-03-19T22:48:31.845Z
Exiting Object::wait: Thread: Thread[Thread One,5,main] at time: 2017-03-19T22:48:31.845Z
我的问题是,
- 还有其他更好的方法吗?
- 在使用 ObjWrapper 时是否存在会中断的边缘情况?
编辑:
我不是在寻找更好的方法来锁定对象。只是更好的方法来记录wait()、notify() 和notifyAll() 方法的调用。
【问题讨论】:
标签: java multithreading logging locking wrapper