I was going through the advanced threads section that java offers regarding locks,I have developed the code..
// 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();
}
}
}
My query is that as we have seen above in class LockDemo that we are calling
new LockThread(lock, "A");
new LockThread(lock, "B");
can’t it be expressed in simple and full terms in coding so that I can grasp more please advise how to express it more simple forms.
It always pisses me off when I see threaded code like this. You are right, it’s a bad example and what it does is not as obvious as it should be. The part that annoys me is the implementation of
Runnableusing itself to start a thread as well as the fact that it starts the thread inside the constructor.I would rewrite it like this:
Now it’s much more clear from
mainthat you are creating two thread tasks (objects whose class implementsRunnable) and using them to start two threads.