练习题之共享变量
一、多线程共享变量
方式一:变量共享
XXX tt = new XXX;
new Thread(tt).start();
new Thread(tt).start();
public class AddMinusOperate { private int j=5; public synchronized void add() { j++; } public synchronized void minus() { j--; } class AddThread implements Runnable { public void run() { add(); } } class MinusThread implements Runnable { public void run() { minus(); } } public static void main(String [] args) { AddMinusOperate addMinusOpt = new AddMinusOperate(); for(int i=0;i<2;i++) { AddThread addThread = addMinusOpt.new AddThread(); new Thread(addThread).start(); MinusThread minusThread = addMinusOpt.new MinusThread(); new Thread(minusThread).start(); } } }
另一种变量共享方式
public class AddMinusExample { public static volatile int j =5; public synchronized void add() { j++; System.out.println("add:"+j); } public synchronized void minus() { j--; System.out.println("add:"+j); } public static void main(String [] args){ for(int i=0;i<2;i++) { new Thread(new Runnable() { public void run() { add(); } },"线程A").start(); new Thread(new Runnable() { public void minus() { minus(); } },"线程B").start(); } } }
方式二:以参数传递的方式共享变量
public class OperateValue { private int operateValue ; /**设置对应getter/setter方法**/ } public AddThread implements Runnable { private OperateValue optValue; public AddThread(OperateValue optValue) { this.optValue = optValue; } public void run() { synchronized(this) { optValue.setOperateValue(optValue.getOperateValue + 1); } } } public MinusThread implements Runnable { private OperateValue optValue; public MinusThread(OperateValue optValue) { this.optValue = optValue; } public void run() { synchronized(this) { optValue.setOperateValue(optValue.getOperateValue -1 1); } } } public TestMain { public static void main(String [] args) { OperateValue optValue = new OperateValue(); optValue.setOperateValue(5); for(int i=0;i<2;i++) { AddThread addThread = new AddThread(optValue); new Thread(addThread).start(); MinusThread minusThread = new MinsThread(optValue); new Thread(minusThread).start(); } } }
方式三:以Executors.newFixedThreadPool(N)方式创建多线程
public class TestMain { private volatile int j = 5; public synchronized add() { j++; System.out.println("Add:"+j); } public synchronized minus() { j--; System.out.println("Minus:" +j); } public AddThread implements Runnable { public void run() { add(); } } public MinusThread implements Runnable { public void run() { minus(); } } public static void main(String[] args) { TestMain main = new TestMain(); ExecutorService executorService = Executors.newFixThreadPool(4); for(int i=0;i<2;i++) { AddThread addThread = main.new AddThread(); executorService.execute(addThread); MinusThread minusThread = main.new MinusThread(); executorService.execute(minusThread); } } }