代码一
- class Ticket extends Thread
- {
- private int tick=100;
- public void run()
- {
- while(tick>0)
- {
- System.out.println(currentThread().getName()+" "+"tick="+tick--);
- }
- }
- }
- class TicketDemo
- {
- public static void main(String[] args)
- {
- Ticket t1=new Ticket();
- Ticket t2=new Ticket();
- Ticket t3=new Ticket();
- Ticket t4=new Ticket();
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 运行结果:
- <b>Thread-1 tick=3</b>
- <b>Thread-1 tick=2</b>
- <b><font color="#ff0000">Thread-1 tick=1</font></b>
- <b>Thread-3 tick=20</b>
- <b>Thread-3 tick=19</b>
- <b>Thread-3 tick=18</b>
- <b>Thread-3 tick=17</b>
- <b>Thread-3 tick=16</b>
- <b>Thread-3 tick=15</b>
- <b>Thread-3 tick=14</b>
- <b>Thread-3 tick=13</b>
- <b>Thread-3 tick=12</b>
- <b>Thread-3 tick=11</b>
- <b>Thread-3 tick=10</b>
- <b>Thread-3 tick=9</b>
- <b>Thread-3 tick=8</b>
- <b>Thread-3 tick=7</b>
- <b>Thread-3 tick=6</b>
- <b>Thread-3 tick=5</b>
- <b>Thread-3 tick=4</b>
- <b>Thread-3 tick=3</b>
- <b>Thread-3 tick=2</b>
- <font color="#ff0000">Thread-3 tick=1</font>
复制代码 发现运结果中两处红色的地方相同,但是平时卖票窗口不会卖出两张相同的票,不合实际,那么将代码一改为代码二试一下:
代码二
- <b>class Ticket extends Thread</b>
- <b>{</b>
- <b> private </b><font color="#ff0000">static</font><b> int tick=100;</b>
- <b> public void run()</b>
- <b> {</b>
- <b> while(tick>0)</b>
- <b> {</b>
- <b> System.out.println(currentThread().getName()+" "+"tick="+tick--);</b>
- <b> }</b>
- <b> }</b>
- <b>}</b>
- <b>class TicketDemo</b>
- <b>{</b>
- <b> public static void main(String[] args) </b>
- <b> {</b>
- <b> Ticket t1=new Ticket();</b>
- <b> Ticket t2=new Ticket();</b>
- <b> Ticket t3=new Ticket();</b>
- <b> Ticket t4=new Ticket();</b>
- <b> t1.start();</b>
- <b> t2.start();</b>
- <b> t3.start();</b>
- <b> t4.start();</b>
- <b> }</b>
- <b>}</b>
复制代码
运行结果如下:
- Thread-1 tick=50
- Thread-2 tick=51
- Thread-1 tick=46
- Thread-0 tick=47
- Thread-3 tick=48
- Thread-0 tick=43
- Thread-1 tick=44
- Thread-2 tick=45
- Thread-1 tick=40
- Thread-0 tick=41
- Thread-3 tick=42
- Thread-3 tick=36
- Thread-0 tick=37
- Thread-0 tick=34
- Thread-0 tick=33
- Thread-0 tick=32
- Thread-0 tick=31
- Thread-0 tick=30
- Thread-0 tick=29
- Thread-0 tick=28
- Thread-0 tick=27
- Thread-0 tick=26
复制代码 发现使用了静态之后就避免了这个问题,但是静态因为常驻内存,所以也不推荐使用这种方式,那么问题来了,该如何解决这个问题呢?
代码三
- class Ticket extends Thread
- {
- private static int tick=100;
- public void run()
- {
- while(tick>0)
- {
- System.out.println(currentThread().getName()+" "+"tick="+tick--);
- }
- }
- }
- class TicketDemo
- {
- public static void main(String[] args)
- {
- Ticket t1=new Ticket();
- //Ticket t2=new Ticket();
- //Ticket t3=new Ticket();
- //Ticket t4=new Ticket();
- t1.start();
- t1.start();
- t1.start();
- t1.start();
- }
- }
复制代码 编译通过,运行时结果没有问题,但是给出如下提示:
- Thread-0 tick=1
- Exception in thread "main" java.lang.IllegalThreadStateException
- at java.lang.Thread.start(Unknown Source)
- at TicketDemo.main(TicketDemo.java:22)
复制代码
即为程序中创建多个相同名称的线程造成的。那么还有没有更好的办法呢?请看下一篇多线程_06 ,引进多线程的另一种创建方式。
|