マルチスレッド(3)スレッドクラスと一般的なメソッド

まず、Threadクラスのいくつかのプロパティ

ここに画像の説明を挿入

⭐①IDはスレッドの一意の識別子であり、異なるスレッドが繰り返されることはありません。②名前はさまざまなデバッグツールで使用されます
。③ステータスはスレッドの現在の状況を示します。以下でさらに説明します。⭐④優先スレッドは、理論的にはスケジュールが簡単です。⑤デーモンスレッド(バックグラウンドスレッド)については、1つのことを覚えておく必要があります。プロセスのすべての非バックグラウンドスレッドが終了すると、JVMは実行を終了します。✧実行されているかどうか、つまり、実行メソッドの実行が終了したかどうかを簡単に理解できるかどうか。スレッドの中断の問題




プロパティ:state-getState()

  Thread thread = new Thread(() ->{
    
    
            System.out.println("当前线程的状态1" + Thread.currentThread().getState());
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        });
        System.out.println("当前线程的状态2" + thread.getState());
        thread.start();

属性:IDと名前– getId()とgetName()

/**
 * 线程属性
 * ID和名称 ;ID一定是不同的,是动态分配的
 * 线程名称手动设置
 */
public class ThreadDemo11 {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                Thread t = Thread.currentThread();
                System.out.println("线程ID" + t.getId());
                System.out.println("线程名称" + t.getName() );
            }
        });
        thread.start();
    }
}

属性:priority-getPriority()

/**
 * 获取优先级
 */
public class ThreadByPriority {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                // 得到当前线程,并打印线程的优先级
                Thread thread1 = Thread.currentThread();
                System.out.println("线程优先级1:" + thread1.getPriority());
            }
        });
        System.out.println("线程优先级2:" + thread.getPriority());
        thread.start();
    }
}

属性:スレッドをデーモン化するかどうか-isDaemon()

 //在主线程创建子线程
        Thread t = new Thread(()->{
    
    
            Thread t1 = Thread.currentThread();
            System.out.println(t1.getName() + "是否守护线程" + t1.isDaemon());
            // 创建子线程
            Thread tt1 = new Thread(() -> {
    
    
                Thread cThread2 = Thread.currentThread();
                System.out.println(cThread2.getName() + "——是否守护线程:" + cThread2.isDaemon());
            }, "子线程的子线程1");
            tt1.start();
        },"子线程1");

属性:生きているかどうか-isAlive()

/**
 * 线程是否存活 isAlive() -while循环
 */
public class DaemonThreadAlive {
    
    
    public static void main(String[] args) {
    
    
        Thread t = new Thread(() ->{
    
    
          for(int i=0;i < 10;i++){
    
    
              try {
    
    
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
    
    
                  e.printStackTrace();
              }
          }
            System.out.println("执行完了");
        });
        t.start();
        //判断是否存活
        while(t.isAlive()){
    
    
        }
        System.out.println("确认执行完了");
    }
}

次に、スレッドを開始します--start()

スレッドオブジェクトは、LiSiとWangWuを呼び出したと見なすことができます。
そして、start()メソッドを呼び出すことは、「Go!」と叫ぶことであり、スレッドは本当に独立して実行できます。

  Thread thread = new Thread(()->{
    
    
      //业务代码
    Thread thread3 = Thread.currentThread();
    System.out.println("名称" + thread3.getName());
  });
  //启动线程
  thread.start();

第三に、スレッドを中断する方法

現在、2つの一般的な方法があります。

1.共有マークアップを介して通信する

//カスタム識別子を宣言し
ますprivatevolatilestatic boolean flag = false;

/**
 * 自定义标识符终止线程
 */
public class InterruptThread1 {
    
    
    //声明一个自定义标识符
    private volatile static boolean flag = false;
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(() -> {
    
    
            while(!flag){
    
    
                System.out.println("正在转账");
                try {
    
    
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
            System.out.println("差点误了大事");
        });
        thread.start();
        System.out.println("执行结束");
    }
}

フラグがクリアされているかどうか

フラグがクリアされるかどうかはスイッチに似ています
。Thread.isInterrupted()はスイッチを押すのと同じで、スイッチは自動的にポップアップします。これは「フラグのクリア」
と呼ばれます。Thread.currentThread()。isInterrupted()は次のようになります。スイッチを押すその後、スイッチはバウンスしません。これは**「フラグをクリアしない」と呼ばれます。**

2.interrupt()メソッドを呼び出して通知します

ここに画像の説明を挿入

//スレッドを終了します
thread.interrupt();
System.out.println( "トランザクションを終了します");

   thread.start();
   Thread.sleep(1000);

     //终止线程
   thread.interrupt();
   System.out.println("终止交易");
   System.out.println("终止标志位3" + Thread.currentThread().isInterrupted());

3.interruptedとisInterruptedの違い

①interruptedは静的メソッドであり、すべてのプログラムで使用できるグローバルメソッドです。isInterruptedはインスタンスのメソッドです②interruptedは
使用後に識別子をリセットしますisInterruptedはリセットされません

詳細な分析をご覧ください

リンクhttps ://blog.csdn.net/qq_55660421/article/details/123662613 。

第四に、thread-join()を待ちます

次の作業に進む前に、スレッドがその作業を完了するのを待つ必要がある場合があります。たとえば、Li Siは、Zhang Sanの作業が成功した後にのみ作業するかどうかを決定します。現時点では、スレッドの終了を明示的に待機するメソッドが必要です。
ここに画像の説明を挿入

public class ThreadByJoin {
    
    
    public static void main(String[] args) throws InterruptedException{
    
    
        Thread t1 = new Thread(() -> {
    
    
            // 1.张三开始上班
            System.out.println("1.张三开始上班");
            // 2.张三正在上班
            try {
    
    
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            // 3.张三下班
            System.out.println("3.张三下班");
        });
        // 启动程序
        t1.start();
//        while (t1.isAlive()) {
    
    
//        }
        // 等待线程 t1 执行完之后,再执行后面的代码
        t1.join();
        Thread t2 = new Thread(() -> {
    
    
            // 1.李四开始上班
            System.out.println("1.李四开始上班");
            // 2.李四正在上班
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            // 3.李四下班
            System.out.println("3.李四下班");
        });
        t2.start();
    }
}

5、現在のスレッドをスリープ状態にします

スリープスレッドには2つの実装があります。

睡眠を使用して睡眠

また、一連のメソッドにも精通しています。覚えておくべきことの1つは、スレッドのスケジューリングが制御できないため、このメソッドでは、実際のスリープ時間がパラメーターで設定されたスリープ時間以上であることを確認することしかできないということです。

ここに画像の説明を挿入

/**
 * 休眠线程
 */
public class ThreadSleep {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        Thread t = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    Thread.sleep(10*1000);
                } catch (InterruptedException e) {
    
    
                    System.out.println("我接收到了中止执行的通知");
//                e.printStackTrace();
                }
            }
        });
        t.start();
        //休眠线程
        Thread.sleep(1000);
        System.out.println("终止子线程 thread");
        t.interrupt();//终止线程
    }
}

TimeUnitで寝る

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 休眠线程
 */
public class ThreadTimeUtil {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        System.out.println("主线程开始执行了:" + LocalDateTime.now());
        TimeUnit.SECONDS.sleep(3); // 休眠 3s
        System.out.println("主线程又开始执行了:" + LocalDateTime.now());
    }
}

6、現在のスレッドへの参照を取得します

ここに画像の説明を挿入

public class ThreadDemo {
    
    
  public static void main(String[] args) {
    
    
     Thread thread = Thread.currentThread();
     System.out.println(thread.getName());
  }
}

おすすめ

転載: blog.csdn.net/qq_55660421/article/details/123707687