java - 是否可以摆脱 wait()、notify() 和synchronized(obj) {} 并仅使用同步方法?

标签 java multithreading synchronization

我是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/

相关文章:

c# - 强制基方法调用

java - 如何在 Android 上解析 GPS 导航消息

java:抛出多个异常

c# - WPF 追加文本会严重阻塞 UI 线程,但 WinForms 不会?

c++ - 接收到输入时 OpenGL 重绘场景

java - 如何查找从哪些 Method 方法调用以及在其中声明变量

python - 如何将多处理与多线程一起使用?

Android单服务器多客户端数据同步

java - 使用装饰器的简单缓存机制

c# - 将媒体文件上传到 s3 包含自动压缩?