【Java面试题】29 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。

本题并不难,实现方式有很多种,有很多种结构。

方法一:利用内部类实现,两个实现加减的类实现Runnable接口,然后再实现4个具体线程。

代码:

public class ManyThreads {

    private int j;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ManyThreads many = new ManyThreads();
        Inc inc = many.new Inc();
        Dec dec = many.new Dec();
        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(inc);
            t.start();
            t = new Thread(dec);
            t.start();
        }
    }

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

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

    class Inc implements Runnable {

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

    }

    class Dec implements Runnable {

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

    }
}

第二种方式:具体加减操作写在一个类的方法里,没有内部类,用另外一个类去调用。

代码:

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();
        }
    }
    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);
        }

    }
}

 

 

参考资料:

http://www.cnblogs.com/nannanITeye/p/3421943.html

http://blog.csdn.net/u014236541/article/details/51178905

http://aijuans.iteye.com/blog/1847835

posted @ 2017-03-27 14:10  暖阳g  阅读(3799)  评论(0编辑  收藏  举报