我第壹個看到這個100分的,說實話,知道妳是個學生要代碼而已,線程類好久沒練手了,練習壹下而已,否則真不會給妳寫代碼。因為我讀書的時候也發過類似的求助,知道什麽感受。不懂的時候真的沒辦法,所以告訴妳思路。
package cn.thread;
public class Through_out_bridge {
public static void main(String[] args) {
Bridge b = Bridge.getInstance();//實例化橋
//實例化左端9個人,此時所有人都不能過橋,橋的可以狀態標誌為不可以用
for (int i = 1; i <= 9; i++) {
Thread t = new Thread(new Person(false, i, b));
t.start();
}
//實例化右端12個人,此時所有人都不能過橋,橋的可以狀態標誌為不可以用
for( int i=1 ;i<=12;i++)
{
Thread t = new Thread(new Person(true,i,b));
t.start();
}
//橋的可用狀態給左端第10個人,可以自定義給誰
b.state = true;
Thread t = new Thread(new Person(false, 10, b));
}
}
class Person implements Runnable {
public Bridge bridge;//橋
private String hand;//在橋哪壹端
int No;//序號
public Person(boolean side, int i, Bridge bridge) {
this.No = i;
this.bridge = bridge;
if(bridge.state)
{
System.out.println(i+"已經過橋。");
}
if (side) {
this.hand = new String("右");
} else {
this.hand = new String("左");
}
}
//過橋方法
public synchronized void through() throws InterruptedException {
if (bridge.state) {
System.out.println(hand+"邊第"+No + "在過橋");
bridge.open( No);
} else {
bridge.lock(No);
}
}
public void run() {
try {
Thread.sleep(1000);
// System.out.println(No+hand+" 邊已經過橋!");
through();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Bridge {
//可用狀態判斷true:可用
public boolean state = false;
//自行實例化
public static Bridge getInstance() {
return new Bridge();
}
public synchronized void open(int i) throws InterruptedException {
if (state) {
Thread.sleep(1000);
this.state=true;
notify();
}
}
public synchronized void lock(int i) throws InterruptedException {
if (!state) {
this.state=false;
System.out.println(i + " 在等待.");
wait();
}
}
}