码迷,mamicode.com
首页 > 编程语言 > 详细

多线程bug修复

时间:2016-01-22 21:38:26      阅读:230      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!