扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java涓璽hread绫荤殑鏂规硶鎬庝箞浣跨敤

扬州沐宇科技
2024-01-10 20:09:41
Java

Java涓璗hread绫荤殑鏂规硶鍙互閫氳繃鍒涘缓Thread瀵硅薄鏉ヤ娇鐢ㄣ€備互涓嬫槸涓€浜涘父鐢ㄧ殑Thread绫绘柟娉曪細

  1. start()锛氬惎鍔ㄧ嚎绋嬶紝浣垮叾杩涘叆灏辩华鐘舵€侊紝骞舵墽琛宺un()鏂规硶銆?/li>
  2. run()锛氬畾涔夌嚎绋嬬殑鎵ц閫昏緫锛屽彲浠ラ噸鍐欒鏂规硶浠ュ疄鐜板绾跨▼鐨勫姛鑳姐€?/li>
  3. sleep(long milliseconds)锛氫娇褰撳墠绾跨▼浼戠湢鎸囧畾鐨勬绉掓暟銆?/li>
  4. join()锛氱瓑寰呰绾跨▼缁堟銆?/li>
  5. interrupt()锛氫腑鏂嚎绋嬨€?/li>
  6. isInterrupted()锛氬垽鏂嚎绋嬫槸鍚﹁涓柇銆?/li>
  7. getName()锛氳幏鍙栫嚎绋嬬殑鍚嶇О銆?/li>
  8. setName(String name)锛氳缃嚎绋嬬殑鍚嶇О銆?/li>
  9. isAlive()锛氬垽鏂嚎绋嬫槸鍚﹀瓨娲汇€?/li>
  10. yield()锛氫娇褰撳墠绾跨▼璁╁嚭CPU鎵ц鏉冿紝璁╁叾浠栫嚎绋嬫湁鏇村鐨勬満浼氭墽琛屻€?/li>

浠ヤ笅鏄竴涓ず渚嬩唬鐮侊紝灞曠ず浜嗗浣曚娇鐢═hread绫荤殑鏂规硶锛?/p>

public class MyThread extends Thread {
    public void run() {
        // 绾跨▼鐨勬墽琛岄€昏緫
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread " + getName() + ": " + i);
            try {
                sleep(1000); // 绾跨▼浼戠湢1绉?/span>
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        thread1.setName("Thread 1");
        
        MyThread thread2 = new MyThread();
        thread2.setName("Thread 2");

        thread1.start(); // 鍚姩绾跨▼1
        thread2.start(); // 鍚姩绾跨▼2

        try {
            thread1.join(); // 绛夊緟绾跨▼1缁堟
            thread2.join(); // 绛夊緟绾跨▼2缁堟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Main thread finished");
    }
}

浠ヤ笂浠g爜涓紝棣栧厛鍒涘缓浜嗕袱涓狹yThread瀵硅薄锛屽苟璁剧疆瀹冧滑鐨勫悕绉般€傜劧鍚庨€氳繃璋冪敤start()鏂规硶鍚姩绾跨▼锛屽苟鎵цrun()鏂规硶涓殑閫昏緫銆傚湪main鏂规硶涓紝浣跨敤join()鏂规硶绛夊緟涓や釜绾跨▼缁堟锛屾渶鍚庢墦鍗板嚭"Main thread finished"銆?/p>

扫码添加客服微信