gpt4 book ai didi

java线程同步问题

转载 作者:行者123 更新时间:2023-12-02 00:28:48 25 4
gpt4 key购买 nike

想提出一些关于线程同步的疑问。我理解了以下概念同步。但是当我通过多线程实现一个示例java程序时,我无法达到我想要的结果。但最终我通过更改一行代码就达到了结果。但我想知道下面的代码有什么问题。

在这里,当我使用同步块(synchronized block),synchronized(SharedResource.class)时,我可以达到我想要的结果。为什么它不适用于同步方法和同步(this) block ?

public class SharedResource {   
public synchronized void access(String name){

System.out.println(name+" :accessed shared resoure");
System.out.println(name+" doing his job: ");
for(int i = 0; i < 5;i++){
try {
System.out.println(name+": "+ i);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+" :finished doing his job..");

}
}


public class SharedAccessThread implements Runnable {

private String name ;
public SharedAccessThread(String name) {
this.name = name ;
}
@Override
public void run() {
SharedResource resource = new SharedResource();
resource.access(Thread.currentThread().getName());

}

}



public class MultiThreading {

public static void main(String[] args) {

SharedAccessThread thread = new SharedAccessThread(Thread.currentThread().getName());

Thread t1 = new Thread(thread);
t1.setName("A");
Thread t2 = new Thread(thread);
t2.setName("b");
Thread t3 = new Thread(thread);
t3.setName("C");

t1.start();
t2.start();
t3.start();

}

}

The expected out put is below:

A :accessed shared resoure
A doing his job:
A: 0
A: 1
A: 2
A: 3
A: 4
A :finished doing his job..
C :accessed shared resoure
C doing his job:
C: 0
C: 1
C: 2
C: 3
C: 4
C :finished doing his job..
b :accessed shared resoure
b doing his job:
b: 0
b: 1
b: 2
b: 3
b: 4
b :finished doing his job..

但它以一种困惑的方式给出。这意味着 A 访问了共享资源..B 正在做他的工作...等我不想要的。

最佳答案

问题是您正在每个线程内创建一个新的 SharedResource:

@Override
public void run() {
SharedResource resource = new SharedResource();
resource.access(Thread.currentThread().getName());

}

因此,同步 this 或方法本身(与同步 this 相同)会导致每个线程看到不同的锁,因此它没有影响。

在类本身上进行同步是有效的,因为它充当全局锁,因为类本身对于所有线程都是相同的。

为了能够在 this 上同步,您应该使资源成为静态成员,例如:

public class SharedAccessThread implements Runnable {

private String name;
private static SharedResource resource = new SharedResource();

public SharedAccessThread(String name) {
this.name = name ;
}
@Override
public void run() {
resource.access(Thread.currentThread().getName());
}
}

这保证了所有线程都能看到相同的 SharedResource 实例。

关于java线程同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9546477/

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