zoukankan      html  css  js  c++  java
  • 线程共享对象小技巧

    最近无意间get到了一个线程方面的小技巧,挺有意思的,关于线程共享对象。

    最早接触线程的时候,常常念叨的一句概念就是,创建线程有两种方式,继承Thread类,实现Runnable接口(虽然后来发现并不止,还有Callable和线程池)。

    但是具体继承Thread和实现Runnable有什么区别呢?当时学到理论的是,由于java是单继承的,如果继承了Thread类就不能继承其他类,但是实现Runnable接口就不影响。所以更推荐实现接口的方式创建线程,就在前几天的学习中,又发现了一些其他的不同,实现接口的方式创建线程,可以共享对象,但访问当前线程必须用Thread.currentThread(),继承类的方式创建线程则可以使用this关键字来访问当前线程。

    那么想共享对象该怎么操作呢?

    public class TestCode {
    
        public static void main(String[] args) throws InterruptedException {
            ThreadImpl impl = new ThreadImpl();
            Thread thread = new Thread(impl);
            Thread thread2 = new Thread(impl);
            thread.start();
            thread2.start();
            Thread.sleep(10);
            System.out.println(impl.common);
        }
    
        static class ThreadImpl implements Runnable {
            int common = 0;
    
            @Override
            public synchronized void run() {
                common++;
            }
        }
    }

    代码中的impl对象就是被共享的,如果是采用继承Thread的方式创建对象,那结果就可想而知了。代码里名字什么的都是乱起的,不要介意哈。

  • 相关阅读:
    [Angular 2] Handle Reactive Async opreations in Service
    移动应用中的流设计
    Linux/Unix--设备类型
    [CF 276C]Little Girl and Maximum Sum[差分数列]
    Java多态
    Shiro(4)默认鉴权与自定义鉴权
    HDU4667(有错)
    weblogic8.1 登陆5 ip 限制
    [置顶] struts2+hibernate+spring整合(annotation版)
    hdu2159 二维完全背包
  • 原文地址:https://www.cnblogs.com/wxdmw/p/14059769.html
Copyright © 2011-2022 走看看