在同步中,不同的监视对象有不同的目的。以下是一些常见的使用场景及相应的代码示例:
class SharedResource {
private int count = 0;
public synchronized void increment() {
count++;
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
resource.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
resource.increment();
}
});
thread1.start();
thread2.start();
// 等待两个线程执行完毕
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + resource.getCount());
}
}
class Resource1 {
public synchronized void method1(Resource2 resource2) {
System.out.println("Resource1.method1");
// 调用Resource2的方法
resource2.method2();
}
public synchronized void method2() {
System.out.println("Resource1.method2");
}
}
class Resource2 {
public synchronized void method1(Resource1 resource1) {
System.out.println("Resource2.method1");
// 调用Resource1的方法
resource1.method2();
}
public synchronized void method2() {
System.out.println("Resource2.method2");
}
}
public class Main {
public static void main(String[] args) {
Resource1 resource1 = new Resource1();
Resource2 resource2 = new Resource2();
Thread thread1 = new Thread(() -> {
resource1.method1(resource2);
});
Thread thread2 = new Thread(() -> {
resource2.method1(resource1);
});
thread1.start();
thread2.start();
// 等待两个线程执行完毕
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
public static void main(String[] args) {
CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add("Thread 1");
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
list.add("Thread 2");
}
});
thread1.start();
thread2.start();
// 等待两个线程执行完毕
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("List size: " + list.size());
}
}
这些示例展示了不同监视对象在同步中的目的和用法。根据具体的场景和需求,可以选择适合的同步方式和监视对象。