注册 登录
编程论坛 JAVA论坛

2个线程输出12A34B.....5152Z。如何控制顺序???

渐渐鱼 发布于 2018-09-14 10:03, 2112 次点击
程序代码:
public class Link_Thread
{
    public static void main(String []args)
    {
        Object obj = new Object();
        Shuzi x1 = new Shuzi(obj);
        Zimu x2= new Zimu(obj);
        Thread thread1 = new Thread(x1);
        Thread thread2 = new Thread(x2);
        thread1.start();
        thread2.start();
    }
}

class Shuzi implements Runnable
{
    private Object obj;
    public Shuzi(Object obj)
    {
        this.obj=obj;
    }
    public void run()
    {
        synchronized(obj)
        {
            for(int i=1;i<53;i++)
            {
                System.out.print(i);
                if(i%2==0)
                {
                    obj.notifyAll();
                    try
                    {
                    obj.wait();
                    }
                    catch (InterruptedException e)
                    {e.printStackTrace();}
                 }
             }
        }
    }
}

class Zimu implements Runnable
{
    private Object obj;
    public Zimu(Object obj)
    {
        this.obj=obj;
    }
    public void run()
    {
        synchronized(obj)
        {
            for(int i=0;i<26;i++)
                {
                   System.out.print((char)(i+'A'));
                   obj.notifyAll();
                   try
                  {
                     obj.wait();
                  }
                  catch (InterruptedException e)
                    {e.printStackTrace();}
                }
               
        }
    }
   
}


代码实现了输出
12A34B.....
但在执行的过程中也会出现A12B34...这样的情况。
那么,能否固定一个顺序呢?
1 回复
#2
幻紫灵心2018-09-14 16:03
你可以让线程一二在开始执行的时候间隔几十毫秒,这样就不会错了。
而且你的代码正常执行最后不会结束线程,在输出 z 之后就永远wait了。
1