简体   繁体   English

使多个线程使用并更改相同的变量

[英]Make multiple threads use and change the same variable

in my program I need to have multiple threads use and edit the same variable, but it doesn't seem to be working. 在我的程序中,我需要使用多个线程并编辑相同的变量,但它似乎不起作用。 Here is an example of what I mean, this would be my main class. 这是我的意思的一个例子,这将是我的主要课程。

public class MainClass {

  public static int number = 0;
  public static String num = Integer.toString(number);

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of threads.");
    int threads = in.nextInt();
    for (int n = 1; n <= threads; n++) {
      java.lang.Thread t = new Thread();
      t.start();
    }
  }
}

This would be my Thread class: 这将是我的Thread类:

public class Thread extends java.lang.Thread
{
  public void run()
  {
      MainClass.number++;
      System.out.println("Thread started");
      System.out.println(MainClass.num);
  }
}

I wrote this code on the spot, so there may be some errors, but thats ok. 我当场写了这段代码,所以可能会有一些错误,但没关系。 My program basically needs to do something like this, but instead of printing the number plus 1 every time, all the threads simply print the same number, 0, multiple times. 我的程序基本上需要做这样的事情,但不是每次打印数字加1,所有线程只是打印相同的数字,0,多次。 Please help me, thanks. 请帮帮我,谢谢。

In my program I need to have multiple threads use and edit the same variable, but it doesn't seem to be working... 在我的程序中,我需要使用多个线程并编辑相同的变量,但它似乎不起作用......

Anytime multiple threads are updating the same variable you need to worry about memory synchronization. 每当多个线程更新同一个变量时,您需要担心内存同步。 One of the ways that threads get high performance is because each thread utilizes the local CPU memory cache and so may be working with stale copies of variables. 线程获得高性能的方法之一是因为每个线程都使用本地CPU内存缓存,因此可能使用过时的变量副本。 You need to use the synchronized or volatile keywords to force the thread's cache to write any updates to central storage or update its cache from central. 您需要使用synchronizedvolatile关键字强制线程的缓存将任何更新写入中央存储或从中央更新其缓存。

Although this takes care of memory synchronization, it doesn't necessarily protect you from race conditions. 虽然这会处理内存同步,但它并不一定能保护您免受竞争条件的影响。 It is also important to realize that ++ is actually 3 operations: get the current value, increment it, and store it back again. 同样重要的是要意识到++实际上是3个操作:获取当前值,增加它并再次存储它。 If multiple threads are trying to do this, there are thread race-conditions which can cause the ++ operations to be missed. 如果多个线程试图这样做,则存在线程竞争条件 ,这可能导致错过++操作。

In this case, you should use the AtomicInteger class which wraps a volatile int field. 在这种情况下,您应该使用包含volatile int字段的AtomicInteger类。 It gives you methods like incrementAndGet() which do the job of incrementing that field in a thread-safe manner. 它为您提供了incrementAndGet()等方法,它们以线程安全的方式完成递增该字段的工作。

public static AtomicInteger number = new AtomicInteger(0);
...
MainClass.number.incrementAndGet();

Multiple threads can then be incrementing the same variable safely. 然后,多个线程可以安全地递增相同的变量。

Here You go... 干得好...

 import java.util.Scanner;
    import java.util.concurrent.atomic.AtomicInteger;

    public class UpdateVariables
    {
        static int num = 0;
        public static AtomicInteger  atomicInteger = new AtomicInteger(num);


        @SuppressWarnings("resource")
        public static void main(String args[])
        {
            Scanner userInput = new Scanner(System.in);
            System.out.println("Enter Number of Threads: ");
            int getThreadNumber = userInput.nextInt();
            for(int i = 0; i < getThreadNumber; i++)
            {
                PrintThread p = new PrintThread();
                p.start();
            }

        }

    }

    class PrintThread extends Thread
    {
        public void run()
        {
            System.out.println("Thread Started: ");
            System.out.println(UpdateVariables.atomicInteger.incrementAndGet());

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM