简体   繁体   English

Java - 为什么锁在多线程 java 程序中对我的变量不起作用?

[英]Java - Why are the locks not working on my variable in a multithreaded java program?

I am trying to learn concurrency in Java and not getting the desired results, why arent my locks working?我正在尝试学习 Java 中的并发性,但没有得到想要的结果,为什么我的锁不起作用? I have tried every tutorial I can find and it is getting me closer, but not 100%我已经尝试了所有我能找到的教程,它让我更接近,但不是 100%

import java.util.concurrent.locks.*;
public class Concurrent extends Thread {
  private Object lock1;// = new Object();
  // static means the variable is shared by all objects, i.e. global
  static long counter = 0;
  static long threads = 10;
  static long count_each = 1000000;
  //private Object lock1 = new Object();
  private Object lock2 = new Object();
  ReentrantLock lock = new ReentrantLock();

  public synchronized void run() //Helps ++
  //public void run() 
  {    
    //synchronized (lock1) 
    //{
        //lock.lock();
        //Object lock1 = new Object();
        long count = count_each;   // local variable for this thread only
        while (count-- > 0) 
        {   
            //lock.lock();
            //try 
            //{
            Object lock1 = new Object();
            synchronized (lock1)  //Helps ++
            {
                counter++;
            }
            //}
            //finally 
            //{
            //    lock.unlock();
            //}
        }
        //lock.unlock();
    //}

  }

Previous attempts are commented out, I have tried just about every combination of everythnig you see.以前的尝试被注释掉了,我已经尝试了你看到的每一个组合。

Your locks are not static , so every thread uses its own lock what renderes them useless.您的锁不是static的,因此每个线程都使用自己的锁,这使它们变得无用。

If you want concurrency, get rid of locks and synchronize and use AtomicLong instead of long counter (if you just want incrementing operation).如果你想要并发,摆脱lockssynchronize并使用AtomicLong而不是long counter (如果你只想递增操作)。 In your case although you are using threads, your logic executes sequentially.在您的情况下,尽管您使用的是线程,但您的逻辑是按顺序执行的。

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

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