有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式

package thread;

/**
 * 有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:
 * A:1 2 3 4 1 2....
 * B:2 3 4 1 2 3....
 * C:3 4 1 2 3 4....
 * D:4 1 2 3 4 1....
 */
public class Thread1test {
    private static volatile int printKey = 0;
    private static volatile int countLimit = 0;
    private static class Thread1 extends Thread
    {
        Thread1(){}
        @Override
        public void run() {
            while (countLimit<20)
            {
                if(printKey==1)
                {
                    countLimit++;
                    System.out.println(printKey);
                    printKey+=1;
                }
            }
        }
    }

    private static class Thread2 extends Thread
    {
        Thread2(){}
        @Override
        public void run() {
            while (countLimit<20)
            {
                if(printKey==2)
                {
                    countLimit++;
                    System.out.println(printKey);
                    printKey+=1;
                }
            }
        }
    }

    private static class Thread3 extends Thread
    {
        Thread3(){}
        @Override
        public void run() {
            while (countLimit<20)
            {
                if(printKey==3)
                {
                    countLimit++;
                    System.out.println(printKey);
                    printKey+=1;
                }
            }
        }
    }

    private static class Thread4 extends Thread
    {
        Thread4(){}
        @Override
        public void run() {
            while (countLimit<20)
            {
                if(printKey==4)
                {
                    countLimit++;
                    System.out.println(printKey);
                    printKey=1;
                }
            }
        }
    }

    public static void main(String[] args)
    {
        printKey=1;
        Thread1 thread1 = new Thread1();
        thread1.start();
        Thread2 thread2 = new Thread2();
        thread2.start();
        Thread3 thread3 = new Thread3();
        thread3.start();
        Thread4 thread4 = new Thread4();
        thread4.start();

    }
}

 

posted @ 2019-09-12 14:32  wygflying  阅读(474)  评论(0编辑  收藏  举报