1.currentThread()
返回代码段正在被哪个线程调用
public class MyThread extends Thread{
public MyThread(){
System.out.println("构造方法"+Thread.currentThread().getName());
}
@Override
public void run(){
System.out.println("run方法"+Thread.currentThread().getName());
}
}
public static void main (String[] args){
MyThread myThread = new MyThread();
myThread.start();//耗时大
//myThread.run();
}
------------------
构造方法main
run方法Thread-0
-------------------
myThread.run() :立即执行run()方法,不启动新的线程
myThread.start():执行run()方法时机不确定,启动新线程
2.isAlive()
判断当前线程是否存活
public static void main (String[] args){
MyThread myThread = new MyThread();
myThread.start();//耗时大
System.out.println(myThread.isAlice());
}
------------------
true
-------------------
3.sleep(long millis)
在指定时间(毫秒)内让当前“正在执行的线程”休眠(暂停执行),正在执行的线程指的是this.currentThread()返回的线程
public static void main (String[] args){
MyThread myThread = new MyThread();
myThread.start();//耗时大
Thread.sleep(1000)//休眠1秒
System.out.println(myThread.isAlice());
}
------------------
true
-------------------
4.StackTraceElement[] getStackTrace()方法
返回一个表示该线程堆栈跟踪元素数组
5.getID()
获取线程的唯一标识
public static void main (String[] args){
Thread thread = Thread.currentThread()
System.out.println(thread.getId);
}
------------------
1
-------------------
6.interrupt()
调用interrupt仅仅是在当前线程做了一个停止的标记,并不是真正停止线程
interrupted: 测试currentThread()是否中断
isInterrupted:测试this所在类的对象是否中断
public class MyThread extends Thread{
@Override
public void run(){
for(int i; i<500000; i++){
System.out.println("i=" + (i+1));
}
}
public static void main (String[] args){
try{
MyThread myThread = new MyThread();
myThread.start();//耗时大
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否停止"+thread.interrupted()); //当前线程指的是main 等同 Thread。interrupted
System.out.println("是否停止"+thread.isInterrupted())
}catch(InterruptedException e){
e.printStackTrace();
}
}
------------------
是否停止false
是否停止true
-------------------
正确停止线程(抛异常法)
```java
public class MyThread extends Thread{
@Override
public void run(){
try{
for(int i; i<500000; i++){
if(this.interrupted()){
System.out.println("停止");
throw new InterruptedException();
}
System.out.println("i=" + (i+1));
}
System.out.println("我在for下面");
}catch(InterruptedException e){
System.out.println("进入catch");
}
}
public static void main (String[] args){
try{
MyThread myThread = new MyThread();
myThread.start();//耗时大
Thread.sleep(1000);
thread.interrupt();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("end");
}
------------------
i=183977
i=183978
停止
end!
进入catch
-------------------
7.Suspend()/Resume()
suspend()暂停线程 resume()恢复线程的执行
myThread.suspend();
myThread.resume();
8.Yield()
放弃当前的CPU资源,让其他任务去占用CPU执行时间。
放弃的时间不确定,有可能刚刚放弃又获得了CPU时间片
Thread.yield();
9.setProiorty
线程也有优先级,优先级高的先执行,优先级为1到10,超过这个范围抛出异常
myThread.setProiorty(10)