gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:37:11 25 4
gpt4 key购买 nike

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

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

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

非常感谢任何帮助。

谢谢,拉杰什

最佳答案

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

关于java - 多线程环境下如何避免同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5140228/

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