• 多线程bug修复


     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

  • 相关阅读:
    Java枚举和反射
    Java网络编程
    django 中文乱码问题
    chrome 开发人员工具
    js 编码问题
    js 复制内容到剪切板
    网页获取页面上选择的内容
    git命令
    Jquery和Javascript对象之间的转换
    Spring Data Elasticsearch
  • 原文地址:https://www.cnblogs.com/lnas01/p/5152130.html
Copyright © 2020-2023  润新知