多线程——设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。

版权声明:文章来源网络,版权归作者本人所有,如侵犯到原作者权益,请与我们联系删除或授权事宜,如果有误,请联系作者更改,谢谢,本人微信:void666666 https://blog.csdn.net/wt520it/article/details/83928325
package com.com.aaa.addreduceThread;

public class ThreadDemo {
    private int j=1;

    //每次添加1
    private synchronized void ad(){
        j++;
        System.out.println("添加"+j);
    }

    //每次减少1
    private synchronized void red(){
        j--;
        System.out.println("减少"+j);
    }

    private class Add implements Runnable{
        @Override
        public void run() {
            for (int i=0;i<5;i++){
                ad();
            }
        }
    }

    private class Reduce implements Runnable{
        @Override
        public void run() {
            for (int i=0;i<5;i++){
                red();
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo td=new ThreadDemo();
        Thread t=null;
        Add a=td.new Add();
        Reduce r=td.new Reduce();
        for (int i=0;i<2;i++){
            t=new Thread(a);
            t.start();
            t=new Thread(r);
            t.start();
        }
    }
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wt520it/article/details/83928325
今日推荐