并发项目的经历不多,之前没见过参数是Runnable的方法,所以虽然题目本身不难,但还是花了一番力气去理解到底怎么运行调试这段代码,记录一下。
class Foo {
Semaphore twolock = new Semaphore(1);;
Semaphore threelock = new Semaphore(1);
public Foo() {
try {
twolock.acquire();
threelock.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
twolock.release();
}
public void second(Runnable printSecond) throws InterruptedException {
twolock.acquire();
printSecond.run();
threelock.release();
}
public void third(Runnable printThird) throws InterruptedException {
threelock.acquire();
printThird.run();
}
public static void main(String[] args) {
Foo foo = new Foo();
//create a runnable, and then create a thread base on it
//wrap the runnables in foo functions, so they can share the same foo object
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("one");
}
};
Thread t1 = new Thread(() -> {
try {
foo.first(r1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//if runnable is simple, can directly override it in the thread initialization
Thread t2 = new Thread(() -> {
try {
foo.second(() -> System.out.print("two"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t3 = new Thread(() -> {
try {
foo.third(() -> System.out.print("three"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//run threads
try {
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
网友评论