不能设置得这么精确
优先级这东西,全由JVM来定的
用线程的sleep本来就不是一个很精确的运算,因为本身调用sleep也是需要时间的
但是一般的应用足够了,就像神说的一样,你又不是发射人造卫星,不需要精确到1毫秒或者1纳秒
public class ThreadTest
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
private int m=0;
public ThreadTest()
{
t1.start();
t2.start();
}
public static void main(String[] args)
{
ThreadTest t=new ThreadTest();
}
class Thread1 extends Thread
{
public void run()
{
while(true)
{ m++;
System.out.println("线程1");
try {
if(t2.isAlive())
t2.wait();
if(m>5)
{
t1.wait();
t2.notify();
}
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Thread2 extends Thread
{
public void run()
{
while(true)
{
System.out.println("线程2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
先让第一个线程执行,再让第二个线程执行!