`
macheng365
  • 浏览: 28023 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

面试线程题目

阅读更多
package com.study.thread;

public class MyThread
{
    private static Count count = new Count(1);

    private static SubThread s = new SubThread(count);

    /**
     * 子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,
      接着再回到主线程又循环100,如此循环50次,请写出程序。 
     */
    public static void main(String[] args) throws Exception
    {
        Thread t = new Thread(s, "子线程");
        t.start();
        Thread.sleep(1);
        mainFun();
    }


    private static void mainFun()
    {
        synchronized (count)
        {
            while (count.count <= 50)
            {
                for (int i = 0; i < 100; i++)
                {
                    System.out.println(Thread.currentThread().getName() + "执行第" + (i + 1) + "次");
                }
                try
                {
                    count.notify();
                    count.wait();
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }

    static class SubThread implements Runnable
    {
        Count count;


        public SubThread(Count count)
        {
            this.count = count;
        }


        public void run()
        {
            synchronized (count)
            {
                while (count.count <= 50)
                {
                    System.out.println("第" + count.count + "次循环----------------------");
                    count.count++;
                    for (int i = 0; i < 10; i++)
                    {
                        System.out.println(Thread.currentThread().getName() + "执行第" + (i + 1) + "次");
                    }
                    try
                    {
                        count.notify();
                        count.wait();
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class Count
    {
        int count;


        public Count(int count)
        {
            this.count = count;
        }


        public int getCount()
        {
            return count;
        }

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics