By GokiSoft.com|
20:15 25/07/2022|
Java Advanced
[Source Code] Tìm hiểu thread trong Java - C2108L
#CustomThread.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lesson04.sub;
/**
*
* @author QTA
*/
public class CustomThread extends Thread{
String name = "ABC";
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("T3 > " + i + ", name = " + name);
}
}
}
#Main.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lesson04.sub;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author QTA
*/
public class Main {
public static void main(String[] args) {
//Doan chuong trinh
//Main Thread
System.out.println("Start"); //Main thread
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//T1
Thread t1 = new Thread(new Runnable() { //Main
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("T1 > " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
t1.start();//Main & t1
// try {
// // t1.stop();
// t1.join();
// } catch (InterruptedException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
// }
//T2
new Thread(new Runnable() { //Main & t1 =>
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("T2 > " + i);
}
}
}).start();//Main & t1 & t2
try {
// t1.stop();
t1.join();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//T3
CustomThread t3 = new CustomThread();//Main & t1 & t2
t3.start(); //Main & t1, & t2 & t3
System.out.println("End");
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)