我正在浏览java提供的关于锁的高级线程部分,我已经开发了代码..
// A simple lock example.
import java.util.concurrent.locks.*;
class LockDemo {
public static void main(String args[]) {
ReentrantLock lock = new ReentrantLock();
new LockThread(lock, "A");
new LockThread(lock, "B");
}
}
// A shared resource.
class Shared {
static int count = 0;
}
// A thread of execution that increments count.
class LockThread implements Runnable {
String name;
ReentrantLock lock;
LockThread(ReentrantLock lk, String n) {
lock = lk;
name = n;
new Thread(this).start();
}
public void run() {
System.out.println("Starting " + name);
try {
// First, lock count.
System.out.println(name + " is waiting to lock count.");
lock.lock();
System.out.println(name + " is locking count.");
Shared.count++;
System.out.println(name + ": " + Shared.count);
// Now, allow a context switch -- if possible.
System.out.println(name + " is sleeping.");
Thread.sleep(1000);
} catch (InterruptedException exc) {
System.out.println(exc);
} finally {
// Unlock
System.out.println(name + " is unlocking count.");
lock.unlock();
}
}
}
我的疑问是,正如我们在课堂上看到的那样LockDemo
,我们正在调用
new LockThread(lock, "A");
new LockThread(lock, "B");
不能在编码中用简单和完整的术语来表达,以便我能掌握更多请指教如何用更简单的形式表达它。