volatile的概念:Volatile关键字的主要作用是使变量在多个线程之间可见,使得在多线程之间可以进行变量的变更。
模拟的场景:新建一份课程科目信息,当线程1新建一个课程后,线程2在新建的该课程下添加科目。
package com.bfxy.thread.core.mycollection; import java.util.ArrayList; import java.util.List; public class MyVolatile { volatile Courses courses = new Courses();//课程 volatile Integer a = 1; //新增课程 public void addcourses(){ courses.setCourses_id(1); courses.setCourses_name("托福"); } //新增科目 public void addsubjects(){ Subject sub1 = new Subject(); sub1.setSub_id(1); sub1.setSub_name("口语"); Subject sub2 = new Subject(); sub2.setSub_id(2); sub2.setSub_name("听力"); List<Subject> subjects = new ArrayList<Subject>(); subjects.add(sub1); subjects.add(sub2); courses.setSubjects(subjects); a = 0; } public Courses getCourses() { return courses; } public void setCourses(Courses courses) { this.courses = courses; } public Integer getA() { return a; } public void setA(Integer a) { this.a = a; } public static void main(String[] args){ /** * 新建一份课程科目信息,当线程1新建一个课程后,线程2在新建的该课程中添加科目。 */ MyVolatile myVolatile = new MyVolatile(); //线程1新增课程 Thread t1 = new Thread(new Runnable() { @Override public void run() { myVolatile.addcourses(); } }); //线程2新增科目 Thread t2 = new Thread(new Runnable() { @Override public void run() { while (myVolatile.getA() == 1){//新增科目完成修改为0,循环结束 对a变量可见 if (myVolatile.getCourses().getCourses_id() != null && myVolatile.getCourses().getCourses_name() != null && myVolatile.getCourses().getCourses_name() != ""){//判断对课程实体类可见 myVolatile.addsubjects(); }else{ System.out.println("false"); } } } }); t1.start(); t2.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //获取新增后的结果 if (myVolatile.getCourses() != null){ System.out.println("课程id: "+myVolatile.getCourses().getCourses_id()); System.out.println("课程name:"+myVolatile.getCourses().getCourses_name()); if (myVolatile.getCourses().getSubjects() != null && myVolatile.getCourses().getSubjects().size()>0){ for (Subject subject:myVolatile.getCourses().getSubjects()){ System.out.println("该课程下的科目id:"+subject.getSub_id()); System.out.println("该课程下的科目name:"+subject.getSub_name()); } } }else{ System.out.println("课程为空"); } } }
执行结果: