【问题标题】:Implementing a shared variable for all the threads?为所有线程实现共享变量?
【发布时间】:2014-10-05 01:35:51
【问题描述】:

我正在实施一个项目,该项目要求所有测试都更新到特定变量。 有没有办法实现一个可以被所有线程访问的共享变量(在使用 Maven 的并行测试期间)?

如果是这样,请与我分享你的想法?

【问题讨论】:

标签: java multithreading maven thread-safety


【解决方案1】:

首先,定义一个包含此类变量的类,或者它也可以在您的线程(派生)类中。

class Particular {
    static int count=0;
    public static synchronized static inc(){
        count++;
    }
    public static synchronized int getCount(){
        return count;
    }
}

然后,您可以使用Particular.inc();Particular.getCount(); 访问计数 更高级的是,您可以使用 Singleton 设计模式来确保线程安全。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 2018-08-28
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    相关资源
    最近更新 更多