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

    }
}
复制代码

 

posted @ 2018-04-10 09:29  十月围城小童鞋  阅读(139)  评论(0编辑  收藏  举报