设计四个线程,其中两个线程每次对j加1,另外两个线程每次对j减1

public class ManyThreads2 {
    private int j = 0;

    public synchronized void inc() {
        j++;
        System.out.println(Thread.currentThread().getName() + "inc" + j);
    }

    public synchronized void dec() {
        j--;
        System.out.println(Thread.currentThread().getName() + "dec" + j);
    }

}
public class MyTest {

    private ManyThreads2 many = new ManyThreads2();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyTest myTest = new MyTest();
        myTest.test();
    }

    public void test() {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < 20; i++) {
                        many.inc();
                    }
                }

            }).start();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    for (int i = 0; i < 20; i++) {
                        many.dec();
                    }
                }

            }).start();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/cn-chy-com/p/10840364.html
今日推荐