线程常用操作方法

前面学习了线程的实现,接下来看看线程的常用操作方法。


1.线程的命名和取得。

在Thread类中提供了以下方法实现线程名称的操作


.构造方法:public Thread(ThreadGroup group, Runnable target, String name)
.设置名字:public final void setName(String name)  
.取得名字: public final String getName()

线程的执行状态本身是不确定的状态,所以如果要取得线程的名字的话,唯一能做的是取得当前执行的线程的名字,Thread类里提供了这样的方法。

public static Thread currentThread()

范例:

class MyThread implements Runnable {
	@Override
	public void run() {
		System.out.println("MyThread线程类: " + Thread.currentThread().getName());
	}
}
public class test {
	public static void main(String[] args) throws Exception {
		MyThread mt = new MyThread();
		new Thread(mt).start();//线程启动调用run() -->输出:MyThread线程类: Thread-0
		mt.run();//直接调用run() -->输出MyThread线程类: main
	}
}

线程一定依附于进程存在的。java命令在jvm上解释某个程序执行的时候,默认都会执行一个jvm的进程,而主方法只是进程中的一个线程。整个程序一直都跑在线程的运行机制上。

每一个jvm至少会启动两个线程:主线程,GC线程。


2.线程的休眠

  休眠方法:public static void sleep(long millis) throws InterruptedException

    millis - 以毫秒为单位的休眠时间。

    InterruptedException -中断异常,休眠时间没有到,线程就被中断了,抛出此异常。此异常非RuntimeException异常,需要处理。

 线程的休眠是有先后顺序的。


3.线程的优先级。

  设置线程优先级:public final void setPriority(int newPriority)

  获取线程优先级:public final int getPriority()

优先级的定义一共有三种:

 线程的最高优先级:public static final int MAX_PRIORITY

 线程最低优先级:public static final int MIN_PRIORITY

 线程的中等优先级:public static final int NORM_PRIORITY

理论上线程的优先级越高越有可能先执行。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章