1. 程式人生 > >經典案例那個什麽多線程--賣票..........................就是好像有點不對~~!先寫下來.有大哥哥,大姐姐幫看下嗎

經典案例那個什麽多線程--賣票..........................就是好像有點不對~~!先寫下來.有大哥哥,大姐姐幫看下嗎

tst dem vat ole 多線程 快的 args str ring

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
}
}
}

經典案例那個什麽多線程--賣票..........................就是好像有點不對~~!先寫下來.有大哥哥,大姐姐幫看下嗎