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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 到处玩的 于 2014-8-7 08:44 编辑

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


1 个回复

倒序浏览
注:因为这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‭();
                }
        }
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马