线程的停止(最好是用标志位的转换来停止线程)
例:
三个模块 线程 线程停止方法 主方法
主方法执行到一定条件 调用 线程停止方法 线程停止执行 主方法继续执行
package Lesson_Thread;
public class Thread_Stop implements Runnable {
//设置标志位 true
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run.....Thread...."+i++);
}
}
//2.设置一个方法,转换标志位
public void stop(){
flag = false;
}
public static void main(String[] args) {
Thread_Stop thread_stop = new Thread_Stop();
new Thread(thread_stop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
thread_stop.stop(); //切换标志为让线程停止
System.out.println("线程该停止了");
}
}
}
}
线程的延迟 (模拟10秒钟倒计时)
1000毫秒=1秒
Thread中的sleep方法单位为毫秒
package Lesson_Thread;
public class daojishi {
public static void main(String[] args) {
tenDown();
}
public static void tenDown(){
int i =10;
while(true){
if(i<=0){
break;
}
System.out.println(i--);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}