|
发表于 2011-10-30 08:40:53
|
显示全部楼层
Re:求助,为什么在运行时数字是无序
楼主,我给你举个例子哈,你在火车站买票,总共有5个窗口,在第一个买地100张票,第99张票就必须让第二个窗口卖么?因为上面的几个线程的优先级都是一样的,所以谁先抢占到cpu谁就先执行输出,他们只要把票卖完就阿了啊!如果你不加上同步代码块在你输出的时候(加上延时就更明显了)就会有负值出现,想必这个你应该明白,如果你加上了同步代码块那么上面的线程就只有第一个是起作用的。下面是代码: Java code
不加同步快:
public class AB {
public static void main(String[] args) {
A s = new A();
Thread t1 = new Thread(s,"售票口->>1");
Thread t2 = new Thread(s,"售票口->>2");
Thread t3 = new Thread(s,"售票口->>3");
Thread t4 = new Thread(s,"售票口->>4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class A implements Runnable {
private int tick = 10;
public void run() {
for(int i = 0;i<100;i++){
if (tick > 0) {
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "......."
+ tick--);
}
}
}
}
输出:售票口->>4.......10
售票口->>2.......9
售票口->>1.......8
售票口->>3.......7
售票口->>4.......6
售票口->>1.......5
售票口->>3.......4
售票口->>2.......3
售票口->>4.......2
售票口->>2.......1
售票口->>3.......0
售票口->>1.......-1
售票口->>4.......-2
加上同步代码块: Java code
package study;
public class AB {
public static void main(String[] args) {
A s = new A();
Thread t1 = new Thread(s,"售票口->>1");
Thread t2 = new Thread(s,"售票口->>2");
Thread t3 = new Thread(s,"售票口->>3");
Thread t4 = new Thread(s,"售票口->>4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class A implements Runnable {
private int tick = 10;
public void run() {
synchronized (this) {
for(int i = 0;i<100;i++){
if (tick > 0) {
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "......."
+ tick--);
}
}
}
}
}
输出结果:
售票口->>1.......10
售票口->>1.......9
售票口->>1.......8
售票口->>1.......7
售票口->>1.......6
售票口->>1.......5
售票口->>1.......4
售票口->>1.......3
售票口->>1.......2
售票口->>1.......1
这下楼主应该明白了吧 |
|