yield方法,暂停调用线程,释放本次执行权。
下面如果不调用yield方法将会一直只执行一个线程.
public class Test
{
public static void main(String[] args)
{
MyRun mr = new MyRun();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t1.start();
t2.start();
}
}
class MyRun implements Runnable
{
@Override
public void run()
{
while (true)
{
synchronized (this)
{
System.out.println("线程名称:" + Thread.currentThread().getName());
try
{
Thread.sleep(100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
Thread.yield();
}
}
}
} |