线程操作的有关方法
一、Thread类中的主要方法
序号 |
方法名称 |
类型 |
描述 |
1 |
public Thread(Runnable target) |
构造 |
接收Runnable接口子类对象,实例化Thread对象 |
2 |
public Thread(Runnable target, String name) |
构造 |
接收Runnable接口子类对象,实例化Thread对象,并设置线程名称。 |
3- |
public Thread(String name) |
构造 |
实例化Thread对象,并设置线程名称。 |
4 |
public static Thread curentThread() |
普通 |
返回目前正在执行的线程 |
5 |
public final String getName() |
普通 |
返回线程的名称 |
6 |
public final int getPriority() |
普通 |
返回线程的优先级 |
7 |
public boolean isInterrupted() |
普通 |
判断目前线程是否被中断,如果是,返回true,否则返回false |
8 |
public final boolean isAlive() |
普通 |
判断线程是否在活动,如果是,返回true,否则返回false |
9 |
public final void join() throws Interrupted Exception |
普通 |
等待线程死亡 |
10 |
public final synchronized void join(long millis) throws InterruptedException |
普通 |
等待millis毫秒后,线程死亡 |
11 |
public void run() |
普通 |
执行线程 |
12 |
public final void setName(String name) |
普通 |
设定线程名称 |
13 |
public final void setPriority(int newPriority) |
普通 |
设定线程的优先值 |
14 |
public static void sleep(long millis) throws InterruptedException |
普通 |
使目前正在执行的线程休眠millis毫秒 |
15 |
public void start() |
普通 |
开始执行线程 |
16 |
public String toString() |
普通 |
返回代表线程的字符串 |
17 |
public static void yield() |
普通 |
将目前正在执行的线程暂停,允许其他线程执行 |
18 |
public final void setDaemon(boolean on) |
普通 |
将一个线程设置成后台运行 |
二、取得和设置线程名称
1、如果没有设置线程名称,系统会为其自动分配名称,名称的格式为Thread-Xx的形式。
2、在Java中所有的线程都是同时启动的,哪个线程先抢占到了CPU资源,哪个线程就先运行。
3、Java程序每次运行至少启动2个线程,一个是main线程,另一个是垃圾收集线程。
三、判断线程是否启动
eg:isAlive()方法。
四、线程的强制运行
eg:join()方法。
说明:在线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行。
五、线程的休眠
eg:Thread.sleep()方法。
六、中断线程
eg:interrupt()方法。
七、后台线程
eg:setDaemon()方法。
八、线程的优先级
eg:setPriority()方法。
九、线程的礼让
eg:yield()方法。