如何在两个线程之间共享变量

如何在两个线程之间共享变量

本文介绍了如何在两个线程之间共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚继承了一些代码,此代码中的两个线程需要执行系统任务.一个线程应该先于另一个线程执行系统任务.他们不应该一起执行系统任务.这两个线程没有相互引用.

I just inherited some code, two threads within this code need to perform a system task. One thread should do the system task before the other thread. They should not be performing the system task together. The two threads do not have references to each other.

现在,我知道我可以使用某种信号量来实现这一目标.但是我的问题是让两个线程访问此信号量的正确方法是什么.

Now, I know I can use some sort of a semaphore to achieve this. But my question is what is the right way to get both threads to access this semaphore.

我可以创建一个静态变量/方法来创建一个新类:

I could create a static variable/method a new class :

public class SharedSemaphore
{
    private static Semaphore s = new Semaphore (1, true);

    public static void acquire () {
        s.acquire();
    }

    public static void release () {
        s.release();
    }
}

这行得通(对吗?),但这似乎不正确.因为,线程现在可以访问信号量,而无需对其进行引用.这类事情似乎不是良好的编程习惯.我错了吗?

This would work (right?) but this doesn't seem like the right thing to do. Because, the threads now have access to a semaphore, without ever having a reference to it. This sort of thing doesn't seem like a good programming practice. Am I wrong?

更新:

我重命名了两个要获取的performTask方法,另一个重命名了释放方法,因为我觉得这分散了实际问题的注意力.

I renamed the two methods performTask to acquire, and the other one to release, because I felt that was distracting from the actual question.

推荐答案

我认为,您可以使performSystemTask方法synchronized就足够了.

I think, you can make performSystemTask method synchronized and it'll be enough.

这篇关于如何在两个线程之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:10