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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建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();
        }
    }
}

 

以上是关于创建4个线程,两个对j加一,两个对j减一(j两同两内)的主要内容,如果未能解决你的问题,请参考以下文章