A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yepeng0311 中级黑马   /  2016-3-22 10:04  /  773 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
以下程序使用内部类实现线程,对j增减的时候没有考虑顺序问题。

1 个回复

倒序浏览
public class Test2 {
        public static void main(String[] args) {
                Factory factory = new Factory();
                T1 t1 = new T1(factory);
                T2 t2 = new T2(factory);
                Thread thread1 = new Thread(t1, "加线程1");
                Thread thread2 = new Thread(t1, "加线程2");
                Thread thread3 = new Thread(t2, "减线程1");
                Thread thread4 = new Thread(t2, "减线程2");
                thread1.start();
                thread2.start();
                thread3.start();
                thread4.start();
        }
}

class T1 implements Runnable {
        Factory factory = null;

        T1(Factory factory) {
                this.factory = factory;
        }

        @Override
        public void run() {
                while (true) {
                        factory.add();
                        try {
                                Thread.sleep((int) Math.random() * 10);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
        }
}

class T2 implements Runnable {
        Factory factory = null;

        T2(Factory factory) {
                this.factory = factory;
        }

        @Override
        public void run() {
                while (true) {
                        factory.min();
                        try {
                                Thread.sleep((int) Math.random() * 10);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
        }

}

class Factory {
        int j;

        Factory() {
                j = 0;
        }

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

        synchronized void min() {
                j--;
                System.out.println(Thread.currentThread().getName()+":"+j);
        }
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马