提供一段用 synchronized写的代码
时间: 2023-03-07 10:31:52 浏览: 92
java代码-证明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();
}
}
阅读全文