多线程(2)

简单的多线程理解,一个简单的购票,创建4个线程,卖5张票.

package util;


public class Test{

public static void main(String[] args) {
new Test().new Ticket().start();
new Test().new Ticket().start();
new Test().new Ticket().start();
new Test().new Ticket().start();

}

class Ticket extends Thread{

private int tick = 5;


public void run() {
while(true){
if(tick > 0){
System.out.println(Thread.currentThread().getName()+"----"+ tick--);
}
}

}

}



}


打印结果:

Thread-0----5
Thread-1----5
Thread-2----5
Thread-1----4
Thread-0----4
Thread-0----3
Thread-3----5
Thread-3----4
Thread-3----3
Thread-3----2
Thread-3----1
Thread-1----3
Thread-2----4
Thread-2----3
Thread-2----2
Thread-2----1
Thread-1----2
Thread-1----1
Thread-0----2
Thread-0----1


发现每个线程都有5张票卖出,与现实不符,发现在内部类的是,变量tick没有定义静态,修改完之后,

package util;


public class Test{

private static int tick = 5;

public static void main(String[] args) {
new Test().new Ticket().start();
new Test().new Ticket().start();
new Test().new Ticket().start();
new Test().new Ticket().start();

}

class Ticket extends Thread{

public void run() {
while(true){
if(tick > 0){
System.out.println(Thread.currentThread().getName()+"----"+ tick--);
}
}

}

}


}

打印结果:

Thread-0----5
Thread-1----4
Thread-0----3
Thread-2----1
Thread-1----2


一般程勋中不推荐用静态变量,回收时间比较长.


推荐写法:


package util;


public class Test{



public static void main(String[] args) {
Ticket t= new Test().new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();

}

class Ticket implements Runnable{
private  int tick = 5;
public void run() {
while(true){
if(tick > 0){
System.out.println(Thread.currentThread().getName()+"----"+ tick--);
}
}

}

}


}


打印结果:

Thread-0----5
Thread-2----3
Thread-2----1
Thread-1----4
Thread-0----2


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值