30-案例实现
案例实现
根据如下步骤实现本案例。
1.创建一个名为 Task
的类,实现 Runnable
接口:
public class Task implements Runnable {
2.声明一个私有的 Lock
属性,并将其命名为 lock
:
private final Lock lock;
3.实现该类的构造器并初始化它的属性:
public Task (Lock lock) {
this.lock=lock;
}
4.实现 run()
方法:
@Override
public void run() {
System.out.printf("%s: Starting\n",
Thread.currentThread().getName());
5.使用 lock()
方法获取锁:
lock.lock();
6.调用 criticalSection()
方法:
try {
criticalSection();
7.从控制台读取:
System.out.printf("%s: Press a key to continue: \n",
Thread.currentThread().getName());
InputStreamReader converter = new InputStreamReader
(System.in);
BufferedReader in = new BufferedReader(converter);
String line=in.readLine();
} catch (IOException e) {
e.printStackTrace();
8.在 finally
中使用 unlock()
方法释放锁:
} finally {
lock.unlock();
}
}
9.实现 criticalSection()
方法。随机等待一段时间:
private void criticalSection() {
Random random=new Random();
int wait=random.nextInt(10);
System.out.printf("%s: Wait for %d seconds\n",
Thread.currentThread().getName(),wait);
try {
TimeUnit.SECONDS.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
10.实现本案例的主类,创建 Main
并添加 main()
方法:
public class Main {
public static void main(String[] args) {
11.创建一个新的 ReentrantLock
对象并命名为lock。创建10个 Task
对象和10个线程来执行它们:
ReentrantLock lock=new ReentrantLock();
for (int i=0; i<10; i++) {
Task task=new Task(lock);
Thread thread=new Thread(task);
thread.start();
}