鏈変笁涓嚎紼?/span>ID鍒嗗埆鏄?/span>A銆?/span>B銆?/span>C,璇鋒湁澶氱嚎緙栫▼瀹炵幇錛屽湪灞忓箷涓婂驚鐜墦鍗?/span>10嬈?/span>ABCABC…
鐢變簬綰跨▼鎵ц鐨勪笉紜畾鎬э紝瑕佷繚璇佽繖鏍鋒湁搴忕殑杈撳嚭錛屽繀欏繪帶鍒跺ソ澶氱嚎紼嬬殑鍚屾銆?br />
綰跨▼鍚屾鏈変袱縐嶅熀鏈柟娉曪細
錛?錛?span style="font: 7pt 'Times New Roman'"> synchronized
錛?錛?span style="font: 7pt 'Times New Roman'"> wait,notify,notifyAll
鐜板湪鍒嗗埆閲囩敤榪欎袱縐嶆柟娉曟潵瑙g瓟榪欓亾棰樼洰銆?/span>
/**
* @author闄堟柊姹?http://www.tkk7.com/hankchen
* 2009-12-28 涓嬪崍01:57:04
*/
/**
*閲囩敤澶氱嚎紼嬫妧鏈墦鍗?/span>10嬈?/span>“ABC”錛屽嵆“錛★饑錛o肌錛跡...”
* 瀹炵幇鏂瑰紡錛堜竴錛夊埄鐢?/span>synchronized鍏抽敭瀛楀疄鐜?/span>
*/
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;
}
}
鏂規硶錛堜簩錛?/span>綰跨▼綾諱慨鏀瑰涓嬶紝鍏朵粬綾諱竴鏍鳳細
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錛?br />