天天看点

java线程编程

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();
    }
}           

复制