class MyThread implements Runnable{
public void run(){
for(int i = 0;i < 10;i++){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程:"+Thread.currentThread().getName()+",i="+i);
}
}
}
public class ticket{
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
}
}
线程让步方法yield()
线程从运行态到就绪
线程让步:暂停执行当前的线程对象,并执行其他线程
yield()方法会让当前线程交出CPU,同样不会释放锁
yield()方法无法控制具体交出CPU的时间
只能让拥有相同优先级的线程有获取CPU的机会
class MyThread implements Runnable{
public void run(){
for(int i = 0;i<10;i++){
Thread.yield();
System.out.println("当前线程:"+Thread.currentThread().getName()+",i="+i);
}
}
}
public class ticket{
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
}
}