面接スレッドのテーマ

2840 ワード

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

    }

}