Java程序员修炼之道的代码 https://download.csdn.net/download/penker_zhao/13452596 重温埃文斯的Java程序员修炼之道,在第三章中运行示例,发现运行了几次不能死锁,所以改了下代码,让其产生死锁,具体死锁原因,请自行浏览书本获取:
package com.java7developer.chapter4;
public class DeadlockMicroBlogNode implements SimpleMicroBlogNode {
private static Update getUpdate(String s) {
Update.Builder b = new Update.Builder();
b.updateText(s).author(new Author("Ben"));
return b.build();
}
private final String ident;
public DeadlockMicroBlogNode(String ident_) {
ident = ident_;
}
public String getIdent() {
return ident;
}
@Override
public synchronized void propagateUpdate(Update upd_,
SimpleMicroBlogNode backup_) {
System.out.println(ident + ": recvd: " + upd_.getUpdateText()
+ " ; backup: " + backup_.getIdent());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
backup_.confirmUpdate(this, upd_);
}
@Override
public synchronized void confirmUpdate(SimpleMicroBlogNode other_,
Update update_) {
System.out.println(ident + ": recvd confirm: " + update_.getUpdateText()
+ " from " + other_.getIdent());
}
public static void main(String[] a) {
final DeadlockMicroBlogNode local = new DeadlockMicroBlogNode(
"localhost:8888");
final DeadlockMicroBlogNode other = new DeadlockMicroBlogNode(
"localhost:8988");
final Update first = getUpdate("1");
final Update second = getUpdate("2");
new Thread(new Runnable() {
public void run() {
local.propagateUpdate(first, other);
}
}).start();
new Thread(new Runnable() {
public void run() {
other.propagateUpdate(second, local);
}
}).start();
}
}
修改UpdateSorterMain.java文件,让其可以成功运行,
public static void main(String[] args) {
这段代码有几点巧妙,5行代码就有四个知识点,可以仔细品读下:
Collections.shuffle(lu);
Update[] updates = lu.toArray(new Update[0]); // Avoid allocation by passing
// zero-sized array
MicroBlogUpdateSorter sorter = new MicroBlogUpdateSorter(updates);
ForkJoinPool pool = new ForkJoinPool(4);
pool.invoke(sorter);