多线程环境下如何避免同步?

发布于 2024-10-19 13:04:39 字数 1439 浏览 1 评论 0原文

由于共享代码,我面临一个与多线程相关的问题。我想避免同步。我看到了很多与 AtomicInteger & 相关的线程。信号。但还没有清楚地知道什么方式以及到底如何它是比同步更好的选择。

这是我想要确保线程安全的简单代码。 创建线程的类。

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();
}}

由多个线程执行的类。

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());
}}

任何帮助都非常感谢。

谢谢, 拉杰什

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. 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

逆光飞翔i 2024-10-26 13:04:40

避免同步的一种方法是使每个将由多个线程访问的资源不可变。使类/对象不可变可确保其线程安全。

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.

<逆流佳人身旁 2024-10-26 13:04:40

如何避免同步取决于具体情况。由于您的情况是人为的并且没有执行任何需要锁定的操作,因此最简单的方法就是删除锁定,即仅在需要时锁定。 (同时删除不执行任何操作的长循环)然后您的应用程序将运行得更快。

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 i.e. only lock when you need to. (Also remove the long loop which doesn't do anything) Then your application will run much faster.

可爱咩 2024-10-26 13:04:40

尝试避免同步块的两个主要原因是性能和保护自己免受死锁的影响。

使用 synchronize 关键字会产生设置锁和保护同步操作的性能开销。虽然调用同步块会带来性能损失,但当 JVM 必须管理该块的资源争用时,会产生更大的影响。

java.util.concurrent.atomic 中的类可以使用机器级原子指令而不是锁定,这使得它们比使用锁的代码快得多。请参阅 javadoc 了解包以获取有关其工作原理的更多信息。

此外,正如 u3050 提到的,避免可变共享状态对于防止同步需求大有帮助。

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. 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.

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. See the javadoc for the package for more information on how that works.

Also, as u3050 mentioned, avoiding mutable shared state goes a long way to preventing the need for synchronization.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文