文章目录
线程的命名与取得
多线程的运行状态是不确定的,所以对于多线程操作必须有一个明确标识出线程对象的信息,这个信息往往通过名 称来描述。在Thread类中提供有如下的线程名称方法:
NO | 方法名称 | 类型 | 描述 |
---|---|---|---|
1 | public Thread(Runnable target, String name) | 构造 | 创建线程时设置名称 |
2 | public final synchronized void setName(String name) | 普通 | 设置线程名称 |
3 | public String getName() | 普通 | 取得线程名称 |
要想取得线程的对象,在Thread类中提供有一个方法取得当前线程对象:
/**
* Returns a reference to the currently executing thread object.
* @return the currently executing thread.
*/
public static native Thread currentThread();
范例:观察取得线程名称
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10 ; i++) {
System.out.println("当前线程:"+Thread.currentThread().getName()+" ,i = "+i);
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread() ;
new Thread(mt).start(); // 没有设置名字
new Thread(mt).start(); // 没有设置名字
new Thread(mt,"yuisama").start(); // 有设置名字
}
}
通过上述代码发现,如果没有设置线程名字,则会自动分配一个线程名字。需要主要的是,线程名字如果要设置请 避免重复,同时中间不要修改。
范例:观察线程的执行结果
class MyThread implements Runnable {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.run(); // 直接通过对象调用run()方法
new Thread(mt).start(); // 通过线程调用
}
}
通过以上程序我们发现,主方法本身就是一个线程,所有的线程都是通过主线程创建并启动的。
问题:进程在哪?
实际上每当使用了java命令去解释程序的时候,都表示启动了一个新的JVM进程。而主方法只是这个进程上的一个 线程而已。
在讲线程的其他常用方法以前,先来看张图:
线程休眠 sleep()方法
线程休眠:指的是让线程暂缓执行一下,等到了预计时间之后再恢复执行。
线程休眠会交出CPU,让CPU去执行其他的任务。但是有一点要非常注意,sleep方法不会释放锁,也就是说如果当 前线程持有对某个对象的锁,则即使调用sleep方法,其他线程也无法访问这个对象。
方法:
public static native void sleep(long millis) throws InterruptedException
休眠时间使用毫秒作为单位。
范例:处理休眠操作
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000 ; i++) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("当前线程:" + Thread.currentThread().getName()+" ,i = " +i);
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread(