线程礼让是指当前正在运行的线程退出运行状态,暂时将运行权让给优先级相同或更高的线程。
调用yield()方法实现礼让,他会将当前程序转到就绪状态。
yield()方法不抛出任何异常。
class
Test1
implements
Runnable
{
public
void
run
(){
for
(
int
i
=
1
;
i
<=
5
;
i
++){
System
.
out
.
println
(
"running thread: "
+
Thread
.
currentThread
().
getName
()
+
", i = "
+
i
);
Thread
.
currentThread
().
yield
();
}
}
}
class
Test2
implements
Runnable
{
public
void
run
(){
for
(
int
i
=
1
;
i
<=
5
;
i
++){
System
.
out
.
println
(
"running thread: "
+
Thread
.
currentThread
().
getName
()
+
", i = "
+
i
);
}
}
}
public
class
ThreadDemo11
{
public
static
void
main
(
String
[]
args
){
Test1 t1
=
new
Test1
();
Thread th1
=
new
Thread
(
t1
,
"Thread-1"
);
Test2 t2
=
new
Test2
();
Thread th2
=
new
Thread
(
t2
,
"Thread-2"
);
th1
.
start
();
th2
.
start
();
}
}

从理论上,t1线程运行的几率要小于t2线程,因为t1总是让其它线程先执行