我是java新手,我正在尝试了解java并发机制。
假设我需要使用以下指令实现任何并发逻辑:wait()、notify()、synchronized(obj) {...}、synchronized 方法。
是否可以在不使用wait()、notify()和synchronized(obj) {...}的情况下重构代码,而只使用synchronized方法?
例如:
public class AppMe extends Thread
{
public Counter counter;
static class Counter
{
protected int num = 0;
public void increment ()
{
num++;
}
}
@Override
public void run ()
{
synchronized (counter) {
counter.increment();
}
}
public static void main (String[] args)
{
AppMe thread = new AppMe();
thread.counter = new AppMe.Counter();
thread.start();
}
}
可以重构为:
public class AppMe extends Thread
{
public Counter counter;
static class Counter
{
protected int num = 0;
synchronized public void increment ()
{
num++;
}
}
@Override
public void run ()
{
counter.increment();
}
public static void main (String[] args)
{
AppMe thread = new AppMe();
thread.counter = new AppMe.Counter();
thread.start();
}
}
这个例子非常简单,但它展示了在线程运行上下文中不使用 wait()、notify()、synchronized(obj) {...} 的想法。
最佳答案
没有。 synchronized(obj)
可以映射到 synchronized
方法,但是没有任何东西可以让您使用 wait()
或 notify()
.
关于java - 是否可以摆脱 wait()、notify() 和synchronized(obj) {} 并仅使用同步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33387979/