最近看到一道面試題,比較有意思:
有三個線程ID分別是A、B、C,請有多線編程實現(xiàn),在屏幕上循環(huán)打印10次ABCABC…
由于線程執(zhí)行的不確定性,要保證這樣有序的輸出,必須控制好多線程的同步。
線程同步有兩種基本方法:
(1) synchronized
(2) wait,notify,notifyAll
現(xiàn)在分別采用這兩種方法來解答這道題目。
/**
* @author陳新漢 http://www.tkk7.com/hankchen
* 2009-12-28 下午01:57:04
*/
/**
*采用多線程技術打印10次“ABC”,即“ABCABC...”
* 實現(xiàn)方式(一)利用synchronized關鍵字實現(xiàn)
*/
public class XunleiInterviewMultithread {
/**
* @param args
*/
public static void main(String[] args) {
XunleiLock lock = new XunleiLock();
new Thread(new XunleiPrinter("A", lock)).start();
new Thread(new XunleiPrinter("B", lock)).start();
new Thread(new XunleiPrinter("C", lock)).start();
}
}
class XunleiPrinter implements Runnable {
private String name = "";
private XunleiLock lock = null;
private int count=10;
public XunleiPrinter(String name, XunleiLock lock) {
this.name = name;
this.lock = lock;
}
@Override
public void run() {
while(count>0) {
synchronized (lock) {
if (lock.getName().equalsIgnoreCase(this.name)) {
System.out.print(name);
count--;
if (this.name.equals("A")) {
lock.setName("B");
} elseif (this.name.equals("B")) {
lock.setName("C");
} elseif (this.name.equals("C")) {
lock.setName("A");
}
}
}
}
}
}
class XunleiLock
{
public String name = "A";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
方法(二)線程類修改如下,其他類一樣:
class XunleiPrinter2 implements Runnable {
private String name = "";
private XunleiLock lock = null;
private int count=10;
public XunleiPrinter2(String name, XunleiLock lock) {
this.name = name;
this.lock = lock;
}
@Override
public void run() {
while(count>0) {
synchronized (lock) {
while(!lock.getName().equalsIgnoreCase(this.name)) {
try{
lock.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print(name);
count--;
if (this.name.equals("A")) {
lock.setName("B");
} elseif (this.name.equals("B")) {
lock.setName("C");
} elseif (this.name.equals("C")) {
lock.setName("A");
}
lock.notifyAll();
}
}
}
}
(友情提示:本博文章歡迎轉載,但請注明出處:陳新漢,http://www.tkk7.com/hankchen)