gpt4 book ai didi

java - 使用不同对象的同步块(synchronized block)

转载 作者:行者123 更新时间:2023-12-02 06:53:16 24 4
gpt4 key购买 nike

我们使用什么对象来获取同步块(synchronized block)上的锁真的很重要吗?

例如,我有 2 个代码片段,如下所示。两者产生相同的输出。我只更改了用于获取同步块(synchronized block)锁定的对象

代码 1:

package test.thread.synchronization;
public class Run1 implements Runnable{
String ts1=null;
public Run1(String ts1){
this.ts1=ts1;
}
@Override
public void run() {
// TODO Auto-generated method stub
run1Print();
}
public void run1Print(){
synchronized(ts1){
for(int i =0;i<10;i++){
System.out.println("run1Print: "+Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}

====

package test.thread.synchronization;
public class Run2 implements Runnable{
String ts1=null;
public Run2(String ts1){
this.ts1=ts1;
}
@Override
public void run() {
// TODO Auto-generated method stub
run2Print();
}
public void run2Print(){
synchronized(ts1){
// System.out.println("Decrement");

for(int i =0;i<10;i++){
System.out.println("run2Print: "+Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}

=====

 package test.thread.synchronization;
public class Ts1 {
public static void main(String[] args) {

// Ts1 ts1 = new Ts1();
String ts1 = "";
Run1 tr1 = new Run1(ts1);
Run2 tr2 = new Run2(ts1);
Thread t1 = new Thread(tr1);
Thread t2 = new Thread(tr2);
t1.start();
t2.start();
}

}

代码2:

package test.thread.synchronization;
public class Run1 implements Runnable{
Ts1 ts1=null;
public Run1(Ts1 ts1){
this.ts1=ts1;
}
@Override
public void run() {
// TODO Auto-generated method stub
run1Print();
}
public void run1Print(){
synchronized(ts1){
for(int i =0;i<10;i++){
System.out.println("run1Print: "+Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}

======

package test.thread.synchronization;
public class Run2 implements Runnable{
Ts1 ts1=null;
public Run2(Ts1 ts1){
this.ts1=ts1;
}
@Override
public void run() {
// TODO Auto-generated method stub
run2Print();
}
public void run2Print(){
synchronized(ts1){
// System.out.println("Decrement");
for(int i =0;i<10;i++){
System.out.println("run2Print: "+Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}

======

package test.thread.synchronization;
public class Ts1 {
public static void main(String[] args) {

Ts1 ts1 = new Ts1();
//String ts1 = "";
Run1 tr1 = new Run1(ts1);
Run2 tr2 = new Run2(ts1);
Thread t1 = new Thread(tr1);
Thread t2 = new Thread(tr2);
t1.start();
t2.start();
}

}

最佳答案

对象类型并不重要,但是您应该在唯一的 final 对象上进行同步,否则您可能会无意中让两个线程在两个不同的对象上同步。

关于java - 使用不同对象的同步块(synchronized block),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17748914/

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