线程共享对象小技巧

最近无意间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的方式创建对象,那结果就可想而知了。代码里名字什么的都是乱起的,不要介意哈。

 

posted @ 2020-11-30 10:05  无心大魔王  阅读(184)  评论(0编辑  收藏  举报