經典案例那個什麼多執行緒--賣票..........................就是好像有點不對~~!先寫下來.有大哥哥,大姐姐幫看下嗎
package javawork;
public class RunnableDemo2 {
public static void main(String[] args) {
Runnable02 ru = new Runnable02();
Thread ru1 = new Thread(ru);
Thread ru2 = new Thread(ru);// 兩個視窗
ru1.start();// 兩個視窗啟動
ru2.start();
}
}
class Runnable02 implements Runnable {
private int num = 16;
Object obj = new Object();
String s = new String();
boolean flag = false;
@Override
public void run() {
while (true) {
// 同步程式碼塊
// flag為 false時 執行同步程式碼塊
if (!flag) {
synchronized (this) {// 同步程式碼快的函式可以是任意函式
if (num > 0) {
System.out.println(Thread.currentThread().getName() + ":" + (num--) + "號票" + "同步程式碼塊++++");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 睡眠0.2S
}
flag = true;
}
// 同步函式
} else {
funtion();
flag = false;
}
}
}
// 同步函式的鎖是This
public synchronized void funtion() {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + ":" + (num--) + "號票" + "同步函式----");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 睡眠0.2S
}
}
}