table of Contents
1. Set and get the thread name
4. Background thread/daemon thread
6, the life cycle of the thread
1. Set and get the thread name
- Get thread name
String getName(): Returns the name of this thread
- Set thread name
void setName(String name): Change the thread name to the parameter name
The thread name can also be set through the constructor
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. Get the thread object
Thread.currentThread()
In the MyRunnable class, because the class does not inherit the Thread class, if you want to get the thread name, you need to do the following:
Thread.currentThread().getName()
3. Thread sleep
4. Background thread/daemon thread
(Spare tire thread)
5. Thread priority
Minimum priority: 1
Priority default value: 5
Maximum priority: 10
public final void setPriority(int newPriority) //设置线程的优先级
public final int getPriority() //获取线程的优先级