Thread.yield可以放弃当前的资源让给CPU去执行
class YieldMethod extends Thread {
@Override
public void run() {
long beginTime = System.currentTimeMillis();
int count = 0;
for(int i=0; i<50000000; i++) {
//放弃当前cpu资源,让给其他任务去占用CPU执行时间。但放弃的时间不确定,有可能刚放弃了又获得了CPU时间
Thread.yield();
count = count + (i + 1);
}
long endTime = System.currentTimeMillis();
System.out.println("用时:" + (endTime - beginTime) + "毫秒!");
}
}
public class ThreadYieldMethod {
public static void main(String[] args) {
YieldMethod y = new YieldMethod();
y.start();
}
}
java中线程分两种一种是用户线程一种是守护线程,守护线程是一种特殊的线程,典型的例子就是垃圾回收线程,当进程中不存在非守护线程时,守护线程自动销毁
class DaemonThread extends Thread {
private int i=0;
@Override
public void run() {
try{
while (true) {
i++;
System.out.println("i=" +(i));
Thread.sleep(1000);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
public class ThreadDaemon {
public static void main(String[] args) {
try {
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
Thread.sleep(5000);
System.out.println("主线程退出,守护进程立刻消亡");
}catch (Exception e) {
e.printStackTrace();
}
}
}