Thread类常用方法

Thread类构造方法:

1.Thread();

2.Thread(String name);

3.Thread(Runable r);

4.Thread(Runable r, String name);

[java]  view plain  copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         /* 
  5.         MyThread thread1 = new MyThread(); 
  6.         MyThread thread2 = new MyThread("MyThread"); 
  7.         thread1.start(); 
  8.         thread2.start(); 
  9.         */  
  10.         MyRunnable run = new MyRunnable();  
  11.         Thread thread3 = new Thread(run);  
  12.         Thread thread4 = new Thread(run, "MyThread");  
  13.         thread3.start();  
  14.         thread4.start();  
  15.     }  
  16.   
  17. }  

常用方法:

start();//启动线程

getId();//获得线程ID

getName();//获得线程名字

getPriority();//获得优先权

isAlive();//判断线程是否活动

isDaemon();//判断是否守护线程

getState();//获得线程状态

sleep(long mill);//休眠线程

join();//等待线程结束

yield();//放弃cpu使用权利

interrupt();//中断线程

currentThread();//获得正在执行的线程对象


守护线程:也叫精灵线程,当程序只剩下守护线程的时候就会退出。

守护线程 的作用类似在后台静默执行,比如JVM的垃圾回收机制,这个就是一个守护线程。而非守护线程则不会。

[java]  view plain  copy
  1. MyRunnable run = new MyRunnable();  
  2.         Thread thread3 = new Thread(run);  
  3.         Thread thread4 = new Thread(run, "MyThread");  
  4.         //设置优先级别  
  5. //      thread3.setPriority(1);  
  6. //      thread3.setPriority(Thread.MAX_PRIORITY);  
  7. //      thread4.setPriority(10);  
  8.         thread3.setPriority(Thread.NORM_PRIORITY);  
  9.         thread4.setPriority(Thread.NORM_PRIORITY);  
  10.         //获得线程的优先级别  
  11.         System.out.println(thread3.getPriority());  
  12.         System.out.println(thread4.getPriority());  
  13.         System.out.println("----------------------");  
  14.         thread3.start();  
  15.         thread4.start();  
  16.         System.out.println("----------------------");  
  17.         System.out.println("线程3是否活动:"+thread3.isAlive());  
  18.         System.out.println("线程4是否活动:"+thread4.isAlive());  
  19.         System.out.println("----------------------");  
  20. //      thread3.setDaemon(true);//设置为守护线程,必须在启动之前设置  
  21.         System.out.println("线程3是否是守护线程:"+thread3.isDaemon());  
  22.         System.out.println("线程4是否是守护线程:"+thread4.isDaemon());  
  23.         System.out.println("----------------------");  
  24.         //获取线程状态  
  25.         System.out.println("线程3的状态:"+thread3.getState());  
  26.         System.out.println("线程4的状态:"+thread4.getState());  
  27.         try {  
  28.             thread4.join();//等待线程4的结束  
  29.         } catch (InterruptedException e) {  
  30.             e.printStackTrace();  
  31.         }  
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值