方案一
利用内部类的方式来实现,直接上代码
import java.util.concurrent.locks.ReentrantLock;
public class Calculation {
private int j = 0;
private ReentrantLock lock = new ReentrantLock();
public void plus() {
try {
lock.lock();
Thread.sleep(500);
j++;
System.out.println(Thread.currentThread().getName() + "对 j 成功加一后值为:" + j);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void reduce() {
try {
lock.lock();
Thread.sleep(500);
j--;
System.out.println(Thread.currentThread().getName() + "对 j 成功减一后j的值为:" + j);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// 加值操作类
private class Plus implements Runnable {
@Override
public void run() {
while (true) {
plus();
}
}
}
// 减值操作类
private class Reduce implements Runnable {
@Override
public void run() {
while (true) {
reduce();
}
}
}
public static void main(String[] args) {
Calculation calculation = new Calculation();
Plus plus = calculation.new Plus();
Reduce reduce = calculation.new Reduce();
for (int i = 1; i <= 4; i++) {
if (i % 2 == 0) {
new Thread(plus, "线程" + i).start();
} else {
new Thread(reduce, "线程" + i).start();
}
}
}
}
在代码中使用到了Lock来保证线程安全,注意使用Lock需要手动开启和释放
方案二
比较有水平,需要知道单例设计模式并运用,单例可以让对象唯一,这样就可以避免使用内部类,可以将加值操作和减值操作抽出来,直接上代码
单例类
import java.util.concurrent.locks.ReentrantLock;
public class Singleton {
private static volatile Singleton singleton = null;
private int j;
private ReentrantLock lock = new ReentrantLock();
private Singleton() {
}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
public void plus() {
try {
lock.lock();
Thread.sleep(500);
j++;
System.out.println(Thread.currentThread().getName() + "对j成功加一后值为:" + j);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void reduce() {
try {
lock.lock();
Thread.sleep(500);
j--;
System.out.println(Thread.currentThread().getName() + "对j减一成功后值为:" + j);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
加值操作类
public class PlusThread implements Runnable {
private Singleton singleton;
public PlusThread() {
singleton = Singleton.getInstance();
}
@Override
public void run() {
while (true) {
singleton.plus();
}
}
}
减值操作类
public class ReduceThread implements Runnable {
private Singleton singleton;
public ReduceThread() {
singleton = Singleton.getInstance();
}
@Override
public void run() {
while (true) {
singleton.reduce();
}
}
}
测试
public class TestThread {
public static void main(String[] args) {
PlusThread plusThread = new PlusThread();
ReduceThread reduceThread = new ReduceThread();
for (int i = 1; i <= 4; i++) {
if (i % 2 == 0) {
new Thread(plusThread, "线程" + i).start();
} else {
new Thread(reduceThread, "线程" + i).start();
}
}
}
}