首页 > 编程语言 > 详细

多线程bug修复

时间:2016-01-22 21:35:24      阅读:295      评论:0      收藏:0      [点我收藏+]
 1 public class ThreadDemo {
 2     public static void main(String[] args) {
 3         ThreadTest test = new ThreadTest();
 4         new Thread(test).start();
 5         new Thread(test).start();
 6         new Thread(test).start();
 7         new Thread(test).start();
 8     }
 9 }
10 
11 class ThreadTest implements Runnable {
12     private volatile int count = 10;
13 
14     public void run() {
15 
16         while (count > 0) {
17             synchronized (this) {
18                 System.out.println(Thread.currentThread().getName() + "   "
19                         + count--);
20             }
21         }
22 
23     }
24 }

Thread-0 10
Thread-3 9
Thread-3 8
Thread-3 7
Thread-3 6
Thread-3 5
Thread-3 4
Thread-3 3
Thread-3 2
Thread-3 1
Thread-2 0
Thread-1 -1
Thread-0 -2

修正案:

 1 public class ThreadDemo {
 2     public static void main(String[] args) {
 3         ThreadTest test = new ThreadTest();
 4         new Thread(test).start();
 5         new Thread(test).start();
 6         new Thread(test).start();
 7         new Thread(test).start();
 8     }
 9 }
10 
11 class ThreadTest implements Runnable {
12     private volatile int count = 10;
13 
14     public void run() {
15 
16         while (count > 0) {
17             synchronized (this) {
18                 if (count > 0) {
19                     System.out.println(Thread.currentThread().getName() + "   "
20                             + count--);
21                 }
22             }
23         }
24 
25     }
26 }

Thread-0 10
Thread-1 9
Thread-1 8
Thread-1 7
Thread-1 6
Thread-0 5
Thread-0 4
Thread-0 3
Thread-0 2
Thread-0 1

 

多线程bug修复

原文:http://www.cnblogs.com/lnas01/p/5152130.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!