您的位置:首页 > 其它

多线程(2)

2016-05-23 16:21 288 查看
简单的多线程理解,一个简单的购票,创建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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: