变量共享是进行线程间通信的常用手段之一,java的内存模型(JMM)解决了可见性和有序性,我们则可以通过线程锁保证原子性。


共享

  • 继承Runnable将变量作为成员变量
  • 将变量定义为final直接访问



有变量:

class ShareData {
    int num = 0;
    
    public synchronized void inrc() {
        num++;
    }
    
    public synchronized void desc() {
        num--;
    }
}

常用的变量共享手段有:

继承Runnable将变量作为成员变量

public static void main(String[] args) {
        ShareData shareData = new ShareData();
        InrcRunnable incrRun = new InrcRunnable(shareData);
        DescRunnable descRun = new DescRunnable(shareData);
        new Thread(incrRun).start();
        new Thread(descRun).start();
}
class InrcRunnable implements Runnable {
    ShareData shareData;
    
    public InrcRunnable(ShareData shareData) {
        this.shareData = shareData;
    }
    
    @Override
    public void run() {
        shareData.inrc();
    }
}
class DescRunnable implements Runnable {
    ShareData shareData;
    
    public DescRunnable(ShareData shareData) {
        this.shareData = shareData;
    }
    
    @Override
    public void run() {
        shareData.desc();
    }
}

将变量定义为final直接访问

public static void main(String[] args) {
    final ShareData shareData = new ShareData();
    new Thread(new Runnable() {
        @Override
        public void run() {
            shareData.inrc();
        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            shareData.desc();
        }
    }).start();
}

jdk1.8不再需要添加final修饰符,这是因为该版本的jdk会隐式的为这些变量添加final修饰词。

PS:
【JAVA核心知识】系列导航 [持续更新中…] 上篇导航:16:volatile关键字:变量可见性与禁止重排序
下篇导航:17.2:线程间通信Exchanger
欢迎关注…