gpt4 book ai didi

Java 多线程和添加静态字段

转载 作者:太空宇宙 更新时间:2023-11-04 13:13:47 26 4
gpt4 key购买 nike

我想编写一个在 main 方法中运行 3 个并发线程的程序,该程序将单词添加到静态字段 infiList类型 ArrayList<String>使用无限循环。

我知道如何创建线程并运行它们,但我不知道如何将它们添加到 infiList 。任何帮助将不胜感激:)

import java.util.ArrayList;

public class Multithreading implements Runnable {

public Multithreading () {
//
}

// Implement the run method in Runnable
public void run() {
// Tell system how to run custom thread

}


public static int infiList(ArrayList<String>) {

return t1;
}

public static void main (String args[]) {

// Create an instance of the class
Multithreading task = new Multithreading();

// Create a thread
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
Thread t3 = new Thread(task);

// Start a thread
t1.start();
t2.start();
t3.start();
}

}

最佳答案

您可以在“run”方法中定义线程将执行的操作,在其中您必须使用单词更新静态列表。

由于并发问题,对线程使用静态列表是一个非常糟糕的主意:线程将更新相同的内存位置,并且将显示覆盖,请使用

Collections.synchronizedList

当您创建列表时

关于Java 多线程和添加静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714251/

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