简体   繁体   English

如何避免在多线程环境中进行同步?

[英]How to avoid synchronize in multithreaded environment?

I am facing one issue related to multithreading because of shared code. 由于共享代码,我面临与多线程相关的一个问题。 I want to avoid syncronization. 我想避免同步化。 I saw so many threads related to AtomicInteger & Semaphore. 我看到了许多与AtomicInteger和Semaphore相关的线程。 But havn't got clear idea about what way and how exactly it is better option than synchronization. 但是,关于同步方式比同步更好的方法还不清楚。

Here is my simple code which i want to make thread safe. 这是我想要使线程安全的简单代码。 Class to create thread. 创建线程的类。

public class ThreadCheck implements Runnable {
TestStaticVar var = new TestStaticVar();
@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        var.holdOn();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void main(String args[]) {
    ThreadCheck t = new ThreadCheck();
    Thread t1 = new Thread(t);
    Thread t2 = new Thread(t);
    t1.setName("A");
    t1.start();
    t2.setName("B");
    t2.start();
}}

Class to be executed by multiple threads. 由多个线程执行的类。

public class TestStaticVar {
Semaphore sem = new Semaphore(1);
public void holdOn() throws InterruptedException{
    sem.acquire();

    System.out.println("Inside Hold on....."+Thread.currentThread().getName()+"==> ");//+i.get());
    try {
          for (long i=0; i<Integer.MAX_VALUE; i++) {

        }
         System.out.println(var1.toString());
    } catch (Exception e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Finished Hold on===="+Thread.currentThread().getName());
              sem.release(1);
    System.out.println("Execution Completed by =====> "+Thread.currentThread().getName());
}}

Any help is highly appriciate. 任何帮助都是非常有用的。

Thanks, Rajesh 谢谢,拉杰什

One way to avoid synchronization is to make every resource immutable which would be accessed by multiple threads. 避免同步的一种方法是使每个资源都是不变的,这将由多个线程访问。 Making class/object immutable makes sure its threadsafe. 使类/对象不可变可确保其线程安全。

How you avoid synchronization depending on the situation. 根据情况如何避免同步。 As your situation is contrived and doesn't do anything which needs locking, the simplest thing to do is remove the lock ie only lock when you need to. 由于您的情况是人为的,不执行任何需要锁定的操作,因此最简单的操作是删除锁定,即仅在需要时锁定。 (Also remove the long loop which doesn't do anything) Then your application will run much faster. (也可以删除不执行任何操作的长循环)然后您的应用程序将运行得更快。

The two main reasons to try to avoid synchronize blocks are performance and protecting yourself from deadlocks. 尝试避免同步块的两个主要原因是性能和保护自己免受死锁的影响。

Using the synchronize keyword involves performance overhead in setting up the locks and protecting the synchronized operation. 使用synchronize关键字会涉及设置锁和保护同步操作的性能开销。 While there is a performance penalty for calling a synchronized block, there's a much bigger hit that gets taken when the JVM has to manage resource contention for that block. 尽管调用同步块会降低性能,但当JVM必须管理该块的资源争用时,就会遭受更大的打击。

The classes in java.util.concurrent.atomic can use machine level atomic instructions rather than locking, making them much faster than code that would use locks. java.util.concurrent.atomic的类可以使用机器级原子指令而不是锁定,从而使它们比使用锁的代码快得多。 See the javadoc for the package for more information on how that works. 有关该程序包的更多信息,请参见javadoc

Also, as u3050 mentioned, avoiding mutable shared state goes a long way to preventing the need for synchronization. 同样,如u3050所述,避免可变的共享状态对于防止同步很有帮助。

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

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