1、getName
- thread.getName()
获取当前运行的线程:Thread.currentThread()
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
MyThread t2 = new MyThread();
t2.start();
}
static class MyThread extends Thread{
@Override
public void run() {
// Thread-1
String name = getName();
System.out.println(name);
// Thread[Thread-1,5,main]
Thread thread = Thread.currentThread();
System.out.println(thread);
// Thread-1
String threadName = thread.getName();
System.out.println(threadName);
}
}
}
2、setName
设置线程名
MyThread t1 = new MyThread();
t1.setName("t1");
t1.start();
MyThread t2 = new MyThread();
t2.setName("t2");
t2.start();
// 构造方法传入线程名
Thread thread = new Thread("thread-name");
3、sleep
让当前线程暂时执行一段时间
- Thread类的静态native方法
public static native void sleep(long millis) throws InterruptedException;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 60; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
4、join
- 把指定的线程加入到当前线程中,可以将两个交替执行的线程合并为顺序执行的线程。
比如在B线程中执行线程A的join方法,a.join(),那么B线程就会暂停执行,先等A线程执行完毕,B线程再重新进入可运行状态。 ```json
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1 start");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 end");
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread2 start");
try {
System.out.println("thread1 join 1");
thread1.join();
System.out.println("thread1 join 2");
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2 end");
}
});
thread2.start();
<a name="Y2DOy"></a>
### 5、yield
- 让当前线程从运行状态RUNNING 转为 就绪状态READY,以允许具有相同优先级的其他线程获得运行机会。
- yield 是一个静态的原生(native)方法。
- yield 告诉当前正在执行的线程把运行机会交给线程池中拥有相同优先级的线程。
- yield 不能保证使得当前正在运行的线程迅速转换到可运行的状态。
- 它仅能使一个线程从运行状态转到可运行状态,而不是等待或阻塞状态。
- 无法保证yield()达到让步目的,因为让步的线程还有可能被线程调度程序再次选中。
<a name="ly1y9"></a>
#### 代码例子
- 下列代码的执行结果
> 可能结果1
> threads1:start
> threads1:end
> threads0:start
> threads0:end
> 可能结果2
> threads0:start
> threads1:start
> threads0:end
> threads1:end
- 结论:无法保证yield()达到让步目的,因为让步的线程还有可能被线程调度程序再次选中。
```json
Thread[] threads = new Thread[2];
for (int i=0;i<2;i++){
int index=i;
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("threads"+index+":start");
Thread.yield();
System.out.println("threads"+index+":end");
}
});
threads[i].start();
}