Java同步帮助请求

发布于 2024-10-31 10:53:50 字数 2125 浏览 2 评论 0原文

我正在为我的应用程序实现一个网络线程管理器。我创建了一个 JUnit 测试,它通过调用以下两个方法快速请求和释放网络线程索引:

protected static final List <Integer> currThreads          = new ArrayList <Integer>();
protected static int                  maxThreads           = 5;
protected static int                  lastGrantedId        = 0;

public static synchronized int reqNewThread(){
    if (currThreads.size() >= maxThreads) return -1;
    ++lastGrantedId;
    currThreads.add(lastGrantedId);
    return lastGrantedId;
}

public static void threadFinished(final int threadId) throws InternalError{
    if (threadId == -1) return;
    synchronized (currThreads) {
        boolean works = currThreads.remove(Integer.valueOf(threadId));
        assert works : ("threadId: " + threadId);
    }
}

线程完成工作后,currThreads 不为空,而是 reqNewThreadthreadFinished 具有相同的调用计数,并且 remove() 始终产生 true。如果我同步整个 threadFinished 方法,它就可以正常工作。问题是——为什么?唯一使用的全局变量已经同步了,不是吗?

JUnit4测试代码:

final int iters = 15;
final Runnable getAndFree = new GetAndFree(iters);
final int sz = 15;
final Thread[] t = new Thread[sz];
for (int i = 0; i < sz; i++)
    t[i] = new Thread(getAndFree);
for (int i = 0; i < sz; i++)
    t[i].start();
for (int i = 0; i < sz; i++)
    t[i].join();
assertEquals(0, currThreads.size());

测试器线程源码:

private class GetAndFree implements Runnable {
    int iters;

    public GetAndFree(int iters){
        this.iters = iters;
    }

    @Override
    public void run(){
        try {
            int id = -1;
            for (int i = 0; i < iters; i++) {
                while ((id = reqNewThread()) == -1) {
                    Thread.sleep(25);
                };
                System.out.println("Strarted: " + id);
                Thread.sleep((long)(Math.random() * 10));
                threadFinished(id);
                System.out.println("Finished: " + id);
            } // for
        } catch(final Exception ex) {
            ex.printStackTrace();
        }
    }
}

I'm implementing a network thread manager for my application. I have created a JUnit test, which rapidly requests and releases a network thread index by invoking the following two methods:

protected static final List <Integer> currThreads          = new ArrayList <Integer>();
protected static int                  maxThreads           = 5;
protected static int                  lastGrantedId        = 0;

public static synchronized int reqNewThread(){
    if (currThreads.size() >= maxThreads) return -1;
    ++lastGrantedId;
    currThreads.add(lastGrantedId);
    return lastGrantedId;
}

public static void threadFinished(final int threadId) throws InternalError{
    if (threadId == -1) return;
    synchronized (currThreads) {
        boolean works = currThreads.remove(Integer.valueOf(threadId));
        assert works : ("threadId: " + threadId);
    }
}

After thread finishes their work, currThreads is not empty, but reqNewThread and threadFinished have the same invocation count and remove() always yield true. If I synchronize the whole threadFinished method, it works fine. Question is - why? The only used global variable is already synchronized, isn't it?

JUnit4 testing code:

final int iters = 15;
final Runnable getAndFree = new GetAndFree(iters);
final int sz = 15;
final Thread[] t = new Thread[sz];
for (int i = 0; i < sz; i++)
    t[i] = new Thread(getAndFree);
for (int i = 0; i < sz; i++)
    t[i].start();
for (int i = 0; i < sz; i++)
    t[i].join();
assertEquals(0, currThreads.size());

Tester thread source:

private class GetAndFree implements Runnable {
    int iters;

    public GetAndFree(int iters){
        this.iters = iters;
    }

    @Override
    public void run(){
        try {
            int id = -1;
            for (int i = 0; i < iters; i++) {
                while ((id = reqNewThread()) == -1) {
                    Thread.sleep(25);
                };
                System.out.println("Strarted: " + id);
                Thread.sleep((long)(Math.random() * 10));
                threadFinished(id);
                System.out.println("Finished: " + id);
            } // for
        } catch(final Exception ex) {
            ex.printStackTrace();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笛声青案梦长安 2024-11-07 10:53:50

唯一使用的全局变量已经同步了,不是吗?

不。

第一个方法是在该方法的封闭类的 Class 对象上进行同步。

第二种方法是在 currThreads 对象上进行同步。

将第一种方法更改为以下方法,它应该可以解决这两种方法的同步问题。

public static int reqNewThread(){
    synchronize(currThread) {
        if (currThreads.size() >= maxThreads) return -1;
        ++lastGrantedId;
        currThreads.add(lastGrantedId);
        return lastGrantedId;
    }
}

The only used global variable is already synchronized, isn't it?

No.

The first method is synchronizing on the Class object for the method's enclosing class.

The second method is synchronizing on the currThreads object.

Change the first method to the following, and it should fix the synchronization issue with respect to these two methods.

public static int reqNewThread(){
    synchronize(currThread) {
        if (currThreads.size() >= maxThreads) return -1;
        ++lastGrantedId;
        currThreads.add(lastGrantedId);
        return lastGrantedId;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文