目录
1、设置和获取线程名称
- 获取线程名称
String getName() : 返回此线程的名称
- 设置线程名称
void setName(String name) : 将线程名称改为参数name
通过构造方法也可以设置线程名称
public class MyThread extends Thread{
public MyThread() {
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
super.run();
for (int i = 0; i < 100; i++) {
System.out.println(getName() + "-------->" + i);
}
}
}
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "##########" + i);
}
}
}
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "============>>>" + i);
}
return null;
}
}
public class Demo {
public static void main(String[] args) {
// MyThread mt1 = new MyThread("子鼠");
// MyThread mt2 = new MyThread("丑牛");
//
mt1.setName("子鼠");
mt2.setName("丑牛");
//
// mt1.start();
// mt2.start();
// MyRunnable mr1 = new MyRunnable();
// MyRunnable mr2 = new MyRunnable();
//
// Thread t1 = new Thread(mr1, "寅虎");
// Thread t2 = new Thread(mr2, "卯兔");
//
// t1.start();
// t2.start();
MyCallable mc1 = new MyCallable();
MyCallable mc2 = new MyCallable();
FutureTask<String> ft1 = new FutureTask<>(mc1);
FutureTask<String> ft2 = new FutureTask<>(mc2);
Thread t1 = new Thread(ft1, "ft1");
Thread t2 = new Thread(ft2, "ft2");
t1.start();
t2.start();
}
}
2、获取线程对象
Thread.currentThread()
在MyRunnable类中,由于该类没有继承Thread类,所以如果要获取线程名称就需要进行如下操作:
Thread.currentThread().getName()
3、线程休眠
4、后台线程/守护线程
(备胎线程)
5、线程的优先级
优先级最小值:1
优先级默认值:5
优先级最大值:10
public final void setPriority(int newPriority) //设置线程的优先级
public final int getPriority() //获取线程的优先级