在现在的项目中多线程成了一个重要的标准 让多个线程并发执行可以挺高运行效率也符合当前人们的习惯 做一件事的空余时候还可以去做别的事 程序都是太基础的东西就不做过多的解释了
package com.java_Thread.date;
import java.util.Date;
public class MyThread extends Thread {
boolean flag = true;
/*
* public void run() { while (flag) { System.out.println("===" + new Date()
* + "==="); try { sleep(1000); } catch (InterruptedException e) { return; }
* } }
*/
public void run() {
while (true) {
String temp = new Date().toString();
String t = temp.substring(11, temp.indexOf('C'));
t = t.trim();
String[] time = t.split(":");
if (time.length == 3) {
System.out.println("现在是" + time[0] + "点" + time[1] + "分"
+ time[2] + "秒");
}
try {
Thread.sleep(2000);//睡眠两秒
} catch (InterruptedException e) {
return;
}
}
}
}
package com.java_Thread.date;
public class TestInterrupt {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
Thread.sleep(10000);//控制打印次数
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
运行结果就是每隔两秒打印一次当前时间