![]() |
#2
幻紫灵心2018-09-14 16:03
|

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();}
}
}
}
}
{
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...这样的情况。
那么,能否固定一个顺序呢?