1.线程的五大状态
2.停止线程
不建议使用stop(),destory()等JDK不推荐使用的方法
可以设置一个状态位来终止线程
package oop;
public class D13 implements Runnable{
private boolean live = true;
@Override
public void run() {
int i = 0;
while(live){
System.out.println("Thread is live " + i++);
}
}
public void stop(){
this.live = false;
System.out.println("Stop thread");
}
public static void main(String[] args) {
D13 d = new D13();
new Thread(d).start();
for(int i=0;i<1000;i++){
if(i==900){
d.stop();
}
System.out.println("Main is running " + i);
}
}
}
3.线程休眠
sleep(int n ) 参数的单位为ms
调用sleep()要catch InterruptedException异常
sleep()完成后,线程进入就绪状态
sleep()不会释放锁
以下代码为用sleep()每隔5s打印一次系统时间
public static void main(String[] args) {
while(true){
try {
Thread.sleep(5000);
Date d = new Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("hh:mm:ss").format(d));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
结果:
4.线程礼让
当前的线程从运行状态转为就绪状态,CPU重新进行调度,但不一定礼让成功,因为CPU有可能选择继续运行该线程。
public class D15 {
public static void main(String[] args) {
TestYield t = new TestYield();
new Thread(t,"Thread A").start();
new Thread(t,"Thread B").start();
}
}
class TestYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " begin");
Thread.yield();
System.out.println(Thread.currentThread().getName() + " end");
}
}
结果:
可以看到Thread B在这一次运行中成功地礼让了A
5.线程强制执行
join() 该线程变为运行状态,且该线程完全执行完,其他线程才能执行
需要抛出异常
public class D16 {
public static void main(String[] args) throws InterruptedException{
TestJoin j = new TestJoin();
Thread t = new Thread(j);
t.start();
for (int i = 0; i < 100; i++) {
if(i==50){
t.join();
}
System.out.println("Main is running " + i);
}
}
}
class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("This thread runs first " + i);
}
}
}
结果: