多线程常用操作可以总结成一下七种。
1、取得当前线程对象: public static native Thread currentThread();
2、线程的命名和取得当前线程的名字:public Thread(Runnable terget,String name)、public String getname()
3、线程休眠 ——sleep(毫秒):让线程暂缓执行,等预计时间后再恢复执行。(不会释放对象锁)
- 线程并非同时休眠,同一时刻的JVM只会运行一个线程。
- 线程休眠会导致线程从运行状态转换到阻塞状态,休眠结束时由阻塞状态转换至就绪状态,再执行由系统调度,无法认为干涉。
- 线程中断为受查异常,必须强制处理。
4、线程让步——yield():当前线程交出CPU,不释放对象锁。
- 交出CPU的时间不可控,只能保证让同等优先级的线程有获得CPU的机会。
- 让当前线程由运行状态转换为就绪状态。
5、join()方法:等待该线程执行结束后继续执行本线程
- 主线程调用join(),会使主线程休眠;
- 使调用该方法的线程结束后再执行主线程。
6、线程停止:
- 设置标志位,让线程正常退出;
- 使用stop()强制停止线程;(JDK 9彻底取消)
- 使用 Thread 中的interrupt()中断线程;
- 正常状态下,Thread.interrupt()可以将线程状态中断,根据此状态人为进行线程终止;
- 线程中出现 wait()、sleep()、join()时调用 Thread.interrupt()时会出现中断异常,必须在catch 快中人为进行线程终止。
7、线程的优先级:
- 优先级越高的线程越有可能先执行,仅仅是可能而已;
- 设置优先级:public final void setpriority (int newpriority);
- 取得优先级:publicfinal int getpriority();
- 线程优先级有继承性:在线程A中启动线程B,则线程B的优先级与线程A相同;
再介绍一个精灵线程——守护线程:
守护线程是一种特殊的线程,只要当前JVM中存在一个非守护线程没有结束,守护线程就不会停止,只有当最后一个非守护线程结束时,守护线程才会停止工作。(垃圾回收线程)
- 判断是否时守护线程:public final boolean isDaemon
- 设置线程为守护线程:public final void setDaemon (boolean on )
class myThread<boolen> implements Runnable{
@Override
public void run() {
int i=0;
try {
while(true) {
i++;
System.out.println(Thread.currentThread().getName()+
" "+i+"是否为守护线程"+Thread.currentThread().isDaemon());
Thread.sleep(1000);}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread()
.getName()+"线程中断了");
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
myThread mt=new myThread();
Thread thread=new Thread(mt,"线程A");
Thread thread1=new Thread(mt,"线程B");
thread.setDaemon(true);
thread.start();
thread1.start();
thread.sleep(3000);
thread1.interrupt();
System.out.println("代码结束");
}
}