- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class TwoThreadAddAndMinus {
- public static void main(String[] args) {
- ScheduledExecutorService ea = Executors.newSingleThreadScheduledExecutor();
- ea.scheduleAtFixedRate(new TestAdd(), 0, 2, TimeUnit.SECONDS);
- ScheduledExecutorService em = Executors.newSingleThreadScheduledExecutor();
- em.scheduleAtFixedRate(new TestMinus(), 0, 5, TimeUnit.SECONDS);
- }
- }
- class TestAdd implements Runnable
- {
- public void run(){
- Num.Add(1);
- }
- }
- class TestMinus implements Runnable
- {
- public void run(){
- Num.Minus(2);
- }
- }
- class Num{
- private static int num = 10;
- public synchronized static void Add(int i){
- num += i;
- System.out.println(num);
- }
- public synchronized static void Minus(int i){
- num -= i;
- System.out.println(num);
- }
- }
复制代码 synchronized方法
或者- package com.test1;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class TwoThreadAddAndMinus {
- public static void main(String[] args) {
- ScheduledExecutorService ea = Executors
- .newSingleThreadScheduledExecutor();
- ea.scheduleAtFixedRate(new TestAdd(), 0, 2, TimeUnit.SECONDS);
- ScheduledExecutorService em = Executors
- .newSingleThreadScheduledExecutor();
- em.scheduleAtFixedRate(new TestMinus(), 0, 5, TimeUnit.SECONDS);
- }
- }
- class TestAdd implements Runnable {
- Num n = Num.getInstance();
- public void run() {
- synchronized (n) {
- n.Add(1);
- }
- }
- }
- class TestMinus implements Runnable {
- Num n = Num.getInstance();
- public void run() {
- synchronized (n) {
- n.Minus(2);
- }
- }
- }
- class Num {
- private static int num = 10;
- private static Num instance = null;
- private Num() {
- }
- public static Num getInstance() {
- if (instance == null)
- instance = new Num();
- return instance;
- }
- public void Add(int i) {
- num += i;
- System.out.println(num);
- }
- public void Minus(int i) {
- num -= i;
- System.out.println(num);
- }
- }
复制代码 synchronized块 相当于加锁 |