Java并发编程实战-学习总结-第一篇(概括)

Java并发编程实战-学习总结-第一篇(概括)看 Java 并发编程实战 有一段时间了 决定将看书学习的过程记录下来 以方便以后查阅及完善 文章中会记录一些书上的知识 同时也会记录一下自己的理解 如有不对的地方希望看到的小伙伴给与指正谢谢 微笑

public class UnsafeSequence { private static int count = 0; public static void main(String[] args) { List 
  
    list = 
   new ArrayList 
   
     (); 
    for ( 
    int i = 
    0; i < 
    10000; i++) { Thread t = 
    new Thread( 
    new Runnable() { @Override 
    public 
    void 
    run() { countSequence(); } }); t.start(); list.add(t); } 
    try { 
    for (Thread t : list) { t. 
    join(); } } 
    catch (InterruptedException e) { e.printStackTrace(); } System. 
    out.println(count); } 
    public 
    static 
    int 
    countSequence() { 
    try { 
    // 模拟程序耗时 
    long l = 
    new Random().nextInt( 
    9) * 
    10; Thread.sleep(l); } 
    catch (InterruptedException e) { e.printStackTrace(); } 
    return count++; } } 
    
  

怎么解决它?有很多方式,最简单直接的方法就是用synchronized关键字,代码修改如下:

public class UnsafeSequence { private static int count = 0; public static void main(String[] args) { List 
  
    list = 
   new ArrayList 
   
     (); 
    for ( 
    int i = 
    0; i < 
    10000; i++) { Thread t = 
    new Thread( 
    new Runnable() { @Override 
    public 
    void 
    run() { countSequence(); } }); t.start(); list.add(t); } 
    try { 
    for (Thread t : list) { t. 
    join(); } } 
    catch (InterruptedException e) { e.printStackTrace(); } System. 
    out.println(count); } 
    public 
    static 
    int 
    countSequence() { 
    try { 
    // 模拟程序耗时 
    long l = 
    new Random().nextInt( 
    9) * 
    10; Thread.sleep(l); } 
    catch (InterruptedException e) { e.printStackTrace(); } 
    /////////这里用了synchronized 关键字,就是这么简单,既保证了可见性又保证了原子性。 synchronized (UnsafeSequence.class) { 
    return count++; } } } 
    
  
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217092.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 上午10:22
下一篇 2026年3月18日 上午10:22


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号