使用run和start的区别
随后补充
isAlive()判断线程是否运行
final boolean isAlive( )
Thread t = new Thread(() -> {
//子线程进行字符串连接操作
int num = 1000;
String s = "";
for (int i = 0; i < num; i++) {
s += "Java";
}
System.out.println("t Over");
});
//开始计时
long start = System.currentTimeMillis();
System.out.println("start = " + start);
t.start();
long end = 0;
//判断线程是否运行,运行继续死循环
while(t.isAlive() == true){//t.getState() != State.TERMINATED这两种判断方式都可以
end = System.currentTimeMillis();
}
System.out.println("end = " + end);
System.out.println("end - start = " + (end - start));
线程仍在运行,isAlive()方法返回true,如果不是则返回false。但isAlive()很少用到,等待线程结束的更常用的方法是调用join()
main线程等待for循环内线程
public void list() {
//线程不可设置为全局变量
List<Thread> threads = new ArrayList<>();
//这个是你多线程并发要处理的数组
List<Device> devices = ShareParamUtil.getList();
for (Device device : devices) {
//下面这个方法是你要并发执行的线程
saveRealDataformDir(threads);
}
try {
for (Thread t : threads) {
t.join();
}
} catch (Exception e) {
e.printStackTrace();
}
threads.clear();
private void saveRealDataformDir(List<Thread> threads){
Thread thread = new Thread(() -> {
//并发处理的逻辑
});
thread.start();
threads.add(thread);