目次
1.スレッド名を設定して取得します
- スレッド名を取得する
String getName():このスレッドの名前を返します
- スレッド名を設定する
void setName(String 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() //获取线程的优先级