用Java代码编写下面程序:分别采用临界区与Lock加锁方式完成两个子线程之间的互斥。在主线程中使用thread创建两个子线程,通过synchronized构造临界区并使两个子线程互斥使用打印进程。采用Lock加锁方式使两个子线程互斥使用全局变量count。
时间: 2024-10-11 15:09:33 浏览: 41
在Java中,我们可以使用synchronized关键字来实现临界区(Lock-free coding)的互斥访问,以及`java.util.concurrent.locks`包下的Lock接口来实现更精细的控制。下面是使用这两种方式实现的示例代码:
首先,使用synchronized关键字(临界区):
```java
public class SynchronizedExample {
private int count = 0;
public void printProcess(int id) {
synchronized (this) {
System.out.println("Thread " + id + " started - " + count);
// 省略实际操作,这里仅模拟时间消耗
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + id + " finished - " + count);
}
}
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
Thread t1 = new Thread(() -> example.printProcess(1));
Thread t2 = new Thread(() -> example.printProcess(2));
t1.start();
t2.start();
}
}
```
接下来,使用ReentrantLock实现Lock方式:
```java
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private int count = 0;
private ReentrantLock lock = new ReentrantLock();
public void printProcess(int id) {
lock.lock();
try {
System.out.println("Thread " + id + " started - " + count);
// 模拟时间消耗
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + id + " finished - " + count);
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
LockExample example = new LockExample();
Thread t1 = new Thread(() -> example.printProcess(1));
Thread t2 = new Thread(() -> example.printProcess(2));
t1.start();
t2.start();
}
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)