创建4个线程,两个对j加一,两个对j减一(j两同两内)


package multithread;

public class MyThread {
    //j变量私有
    private int j;
    //同步的+1方法
    private synchronized void add(){
        j++;
        System.out.println(Thread.currentThread().getName()+"----------> "+j);
    }
    //同步的-1方法
    private synchronized void subtract(){
        j--;
        System.out.println(Thread.currentThread().getName()+"----------> "+j);
    }
    //实现Runnable接口的内部加类
    class Add implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                add();
            }
        }
    }
    //实现Runnable接口的内部减类
    class Subtract implements Runnable{
        
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                subtract();
            }
        }
    }
    
    public static void main(String[] args) {
        //创建外部类和内部类的实例
        MyThread mt = new MyThread();
        Add add = mt.new Add();
        Subtract subtract = mt.new Subtract();
        //循环启动4个线程
        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(add);
            t.start();
            t = new Thread(subtract);
            t.start();
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM