gpt4 book ai didi

java - 线程中的私有(private)成员从另一个线程更改

转载 作者:行者123 更新时间:2023-11-29 04:54:37 25 4
gpt4 key购买 nike

我的第一个问题。 Java 自学成才,非专家。

我有一个主应用程序创建一个管理器线程。管理器将创建工作线程。 Main 会将“Properties”作为参数传递给 Manager。 Manager 会对属性进行一些添加,并将其作为参数传递给每个 Worker。

问题:

实例化辅助对象后,当我更改属于管理器的属性成员时,属于辅助线程的属性成员也会发生变化.由于 Worker 类中的属性是私有(private)成员,我认为它只能在 Worker 类中更改。为什么当我在管理器中进行更改时它会发生变化?我怎样才能避免这个问题?

这里附上一个简单版本的代码:

主.java:

import java.util.Properties;

public class Main {
public static void main(String arg[])
{
Properties properties = new Properties();
properties.put("p1", "v1");
Manager manager = new Manager(properties);
manager.start();
}
}

管理器.java:

import java.util.Properties;

public class Manager {
private Properties properties;

Manager(Properties argProperties)
{
properties = argProperties;
}

public void start()
{
properties.put("workerId", "worker1");
spawnWorker();

try {
Thread.sleep(2000);
}catch(InterruptedException ex){
//do nothing
}

System.out.println("Manager going to change worker ID to 2");
properties.put("workerId", "worker2");
spawnWorker();

try {
Thread.sleep(2000);
}catch(InterruptedException ex){
//do nothing
}

Thread manager = new Thread("manager"){
public void run() {
System.out.println("Manager going to change worker ID to haha");
while(true)
{
try {
properties.put("workerId", "hahaha");
Thread.sleep(1000);
}catch(InterruptedException ex){
//do nothing
}
}
}
};
manager.start();
}

private void spawnWorker()
{
Worker worker = new Worker(properties);
worker.start();
}
}

worker .java:

import java.util.Properties;

public class Worker {
private final Properties properties;
String workerId;

Worker(Properties argProperties)
{
properties = argProperties;
workerId = properties.getProperty("workerId");
}

public void start()
{
Thread worker = new Thread("worker-" + workerId){
public void run() {
while(true)
{
try {
System.out.println(this.getName() + "<->" + properties.getProperty("workerId"));
Thread.sleep(1000);
}catch(InterruptedException ex){
//do nothing
}
}
}
};
worker.start();
}
}

输出:

worker-worker1<->worker1
worker-worker1<->worker1
worker-worker1<->worker1
Manager going to change worker ID to 2
worker-worker2<->worker2
worker-worker1<->worker2
worker-worker2<->worker2
worker-worker1<->worker2
Manager going to change worker ID to haha
worker-worker2<->worker2
worker-worker1<->hahaha
worker-worker2<->hahaha

最佳答案

您正在将相同的 Properties 实例传递给每个 worker。因此每个 worker 都可以改变它的内容。

在生成新工作人员之前,您应该复制属性并将此副本传递给工作人员。

//更多背景:变量修饰符用于声明变量的可见性。不能从外部类访问私有(private)成员。但它可以通过引用(正如您所做的那样,通过构造函数传递引用)或公共(public) getter 公开。因此,可以更改公开的私有(private)成员内容。

可以在这里找到详细信息:

关于java - 线程中的私有(private)成员从另一个线程更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com