synchronized写代码怎么去用
时间: 2023-12-29 21:05:29 浏览: 21
synchronized 是 Java 中的一个关键字,用于实现线程同步。当多个线程访问共享资源时,可能会出现竞态条件(race condition)导致数据不一致或程序崩溃。使用 synchronized 可以保证在同一时刻只有一个线程可以访问共享资源,从而避免竞态条件。
在 Java 中,synchronized 可以用于方法和代码块两种情况。
1. 对于方法:
```java
public synchronized void doSomething() {
// 代码块
}
```
在方法签名中使用 synchronized 关键字,意味着该方法是同步的,即在同一时刻只有一个线程可以访问该方法。
2. 对于代码块:
```java
synchronized (lockObject) {
// 代码块
}
```
在代码块前使用 synchronized 关键字,意味着该代码块是同步的,即在同一时刻只有一个线程可以访问该代码块。lockObject 是一个对象锁,它的作用是控制多个线程的访问。
需要注意的是,使用 synchronized 会降低程序的执行效率,因为它会引入额外的线程切换和锁竞争的开销。因此,在使用 synchronized 时应该避免长时间占用锁,尽量缩小锁的范围,避免死锁等问题的发生。
相关问题
提供一段用 synchronized写的代码
public class SyncExample {
public static void main(String[] args) {
final Object lock = new Object(); Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("Thread 1: Holding lock...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Release lock...");
}
}
}); Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("Thread 2: Holding lock...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Release lock...");
}
}
}); t1.start();
t2.start();
}
}答:public class SyncExample {
public static void main(String[] args) {
final Object lock = new Object(); Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("线程1:持有锁...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("线程1:释放锁...");
}
}
}); Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("线程2:持有锁...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("线程2:释放锁...");
}
}
}); t1.start();
t2.start();
}
}
synchronized锁代码
synchronized关键字可以用于保证多个线程对共享资源的安全访问。当一个线程进入synchronized代码块时,它会尝试获取锁。如果该锁已经被其他线程持有,则进入等待状态,直到锁被释放。以下是使用synchronized锁代码的示例:
```java
public class MyClass {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
// 调用示例
public class Main {
public static void main(String[] args) {
MyClass myObj = new MyClass();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 100000; i++) {
myObj.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 100000; i++) {
myObj.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + myObj.getCount());
}
}
```
在上述示例中,MyClass类中的increment()和getCount()方法都被声明为synchronized。这样,在多个线程同时访问这些方法时,只有一个线程能够获取到对象的锁,保证了count变量的安全更新。