System.out.println(Thread.currentThread().getName());
test.start();
test.start();
多次调用start会出现:
Exception in thread "main" java.lang.IllegalThreadStateException
Thread.sleep(1000);
System.out.println("behind sleep");在Thread.sleep(1000);结束后执行
Run run = new Run();
Thread thread = new Thread(run);
thread.start();
不管是接口类型还是Thread类型,都可以作为Thread构造方法的参数。
多个线程同时操作一个变量会出错,线程不安全。
synchronized可以在任何对象或者方法上加锁
currentThread()方法返回代码正在被哪个线程调用的信息
isAlive()方法判断当前的线程是否处于活动状态(启动但是尚未终止) thread.isAlive()
System.out.println(thread.isAlive()); 线程执行完返回false
停止一个线程有三种方法:
1.使用退出标志,是线程正常退出,也就是run方法执行完毕后终止
2.使用stop,不建议使用
3.使用interrupt
1.this.interrupted():测试当前线程是否已经中断,执行后具有将状态标志清除为false的功能
2.this.isinterrupted():测试线程是否已经中断,不清除状态标志
main(){
thread.interrupt();
}
for (int i = 0;i<500000;i++){
if (this.isInterrupted())
break;
System.out.println(i);
}
System.out.println("这里还是会执行");
加上一个异常,就不执行for后面的语句了,实现了线程的终止
public void run() {
super.run();
try {
for (int i = 0;i<500000;i++){
if (this.isInterrupted())
throw new InterruptedException();
System.out.println(i);
}
System.out.println("这里还是会执行");
}catch (InterruptedException e){
e.printStackTrace();
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有