wait和sleep的区别;
wait要唤醒要释放同步锁;
sleep不要唤醒不释放同步中的锁
都释放CPU的执行权
简称:两要要不要同释放CPU
停止线程:
stop();方法过时;
开启线程一般是循环结构:结束循环就可以结束线程
但是线程有一种冻结状态,循环没有结束就抛出异常此时不能结束循环.
但Thread提过了interrupt()方法来中断线程回到运行状态
class StopDemo implements Runnable{
private boolean flag = true;
public synchronized void run(){
while(flag){
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptException 运行");
flag = false ;
}
System.out.println(Thread.currentThread().getName()+"run....");
}
}
}
public class StopThreaDemo {
public static void main(String args[]){
int in =0;
Thread t = new Thread(new StopDemo());
t.setDaemon(true);
t.start();
while(true){
if(in>=60){
System.out.println("over");
t.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"..."+in++);
}
}
}
守护线程(后台线程):当前台线程结束后台线程自动结束
setDaemon(true);必须在启动线程前调用。
当所有的线程都为守护线程时jvm自动退出
join();等待该线程终止;
setPriority(Thread.MAX_PRIORITY)设置优先级
yield();等待其他线程结束
class Join implements Runnable{
public void run(){
for(int i =0;i<100;i++){
System.out.println(Thread.currentThread().getName()+"run"+i);
}
}
}
public class JoinDemo {
public static void main(String args[]) throws InterruptedException{
Join j = new Join();
Thread t1= new Thread(j,"线程一");
Thread t2= new Thread(j,"线程二....");
//t1.join();
// t1.setPriority(Thread.MAX_PRIORITY);
t1.yield();
t1.start();
t2.start();
for(int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
} |
|