黑马程序员技术交流社区

标题: 设计4个线程,其中两个线程每次对j增加1,另外两个线程... [打印本页]

作者: 到处玩的    时间: 2014-8-6 00:03
标题: 设计4个线程,其中两个线程每次对j增加1,另外两个线程...
本帖最后由 到处玩的 于 2014-8-7 08:44 编辑

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。



作者: 张涛的狂怒    时间: 2014-8-6 00:21
注:因为这4个线程共享J,所以线程类要写到内部类中‭。
加线程:每次对j加一‭。
减线程:每次对j减一‭。‬
public class TestThreads
‭{
        private int j‭=‬1‭;
        //加线程
‭        ‬private class Inc implements Runnable
‭        {
                public void run‭()
                {
                        for(int i‭ = ‬0‭;‬i‭ < ‬10‭;‬i++‭)
                        {
                                inc‭();
                        }
                }
        }
        //减线程
‭        ‬private class Dec implements Runnable
‭        {
                public void run‭()
                {
                        for(int i‭ = ‬0‭;‬i‭ < ‬10‭;‬i++‭)
                        {
                                dec‭();
                        }
                }
        }
        //加1
‭        ‬private synchronized void inc‭()
        {
                j++‭;
                System.out.println(Thread.currentThread‭()‬.getName‭()‬+‭"‬-inc:‭"‬+j‭);
        }
        //减1
‭        ‬private synchronized void dec‭()
        {
                j--‭;
                System.out.println(Thread.currentThread‭()‬.getName‭()‬+‭"‬-dec:‭"‬+j‭);
        }
        //测试程序
‭        ‬public static void main(String‭[] ‬args‭)
        {
                TestThreads test‭ = ‬new TestThreads‭();
                //创建两个线程类
‭                ‬Thread thread‭ = ‬null‭;
                Inc inc‭ = ‬test.new Inc‭();
                Dec dec‭ = ‬test.new Dec‭();
                //启动4个线程
‭                ‬for(int i‭ = ‬0‭;‬i‭ < ‬2‭;‬i++‭)
                {
                        thread‭ = ‬new Thread(inc‭);
                        thread.start‭();
                        thread‭ = ‬new Thread(dec‭);
                        thread.start‭();
                }
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2