本文目錄一覽:
java多線程的幾種實現方法及多窗口售票小程
1、繼承Thread類創建線程
2、實現Runnable介面創建線程
3、實現Callable介面通過FutureTask包裝器來創建Thread線程
4、使用ExecutorService、Callable、Future實現有返回結果的線程
100張票,用java多線程實現3個窗口按順序依次賣票,如何實現
很簡單, 出票里加鎖就行了完整代碼:
public class Test {
public static void main(String[] args) {
for(int i=0; i3; i++){
new Thread(“線程 ” + i){
public void run() {
while(true){
int p = getNumber();
if(p 0 ){
System.out.println(getName() + ” 票號: ” + p);
}else{
System.out.println(“沒票了”);
break;
}
}
};
}.start();
}
}
public static int num = 100; //總票數
/**
* synchronized 同步鎖
* @return
*/
public static synchronized int getNumber(){
if(num 0){
return num –; //如果大於0, 則返回當前票並減少一張
}
return 0;
}
}
java多線程的賣票問題
首先,定義的鎖(lock)不對,必須是同一個鎖,像你這樣用this,new多少個MyThread就有多少個鎖,違反了線程的同步機制;
其次,你如果想要呈現多線程的競爭,不可以在run方法里讓一個線程一直運行而不釋放鎖,應該使用wait()/notify();
以下我稍微修改下,會形成兩個線程交替執行的情形:
public class ThreadTest {
public static Object obj = new Object();
public static int number = 10;// 用static共享票源,不知道可以不,按理說是可以的
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread my = new MyThread();
MyThread my2 = new MyThread();
Thread t1 = new Thread(my2, “2號窗口”);
Thread t2 = new Thread(my, “1號窗口”);
t1.start();
t2.start();
}
static class MyThread implements Runnable {
public void run() {
while (true)
synchronized (obj) {
if (number 0) {
System.out.println(Thread.currentThread().getName()
+ “正在賣票,” + “還剩” + number + “張票”);
number–;
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
break;
}
}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/196364.html