一、多线程共享变量
方法一:以变量共享的方式进行操作
public class AddMinusOperate {
private int j=5;
public synchronized void add() {
j++;
}
public synchronized 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 addMinus = new AddMinusOperate();
AddThread addThread = addMinus.new AddThread();
MinusThread minusThread = addMinus.new MinusThread();
for(int i=0;i<2;i++) {
new Thread(addThread).start();
new Thread(minusThread).start();
}
}
}
方式二、通过多线程值传递的方式进行操作
时间: 2024-10-13 01:55:09