當前位置:編程學習大全網 - 編程語言 - 求JAVA多線程編程代碼

求JAVA多線程編程代碼

測試過了,沒問題。基本思路,實例化壹個橋類,誰得到橋的可用標誌誰過橋。

我第壹個看到這個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();

}

}

}

  • 上一篇:設計壹個程序當單擊窗體時,在窗體上顯示任意壹幅圖片
  • 下一篇:關於小學數學教學反思
  • copyright 2024編程學習大全網