java涓璽hread绫荤殑鏂规硶鎬庝箞浣跨敤
Java涓璗hread绫荤殑鏂规硶鍙互閫氳繃鍒涘缓Thread瀵硅薄鏉ヤ娇鐢ㄣ€備互涓嬫槸涓€浜涘父鐢ㄧ殑Thread绫绘柟娉曪細
- start()锛氬惎鍔ㄧ嚎绋嬶紝浣垮叾杩涘叆灏辩华鐘舵€侊紝骞舵墽琛宺un()鏂规硶銆?/li>
- run()锛氬畾涔夌嚎绋嬬殑鎵ц閫昏緫锛屽彲浠ラ噸鍐欒鏂规硶浠ュ疄鐜板绾跨▼鐨勫姛鑳姐€?/li>
- sleep(long milliseconds)锛氫娇褰撳墠绾跨▼浼戠湢鎸囧畾鐨勬绉掓暟銆?/li>
- join()锛氱瓑寰呰绾跨▼缁堟銆?/li>
- interrupt()锛氫腑鏂嚎绋嬨€?/li>
- isInterrupted()锛氬垽鏂嚎绋嬫槸鍚﹁涓柇銆?/li>
- getName()锛氳幏鍙栫嚎绋嬬殑鍚嶇О銆?/li>
- setName(String name)锛氳缃嚎绋嬬殑鍚嶇О銆?/li>
- isAlive()锛氬垽鏂嚎绋嬫槸鍚﹀瓨娲汇€?/li>
- 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>
相关问答