Estado del hilo
- NUEVO: acaba de crear un hilo sin iniciar
- RUNNABLE: estado de ejecución
- BLOQUEADO: hilo en un estado bloqueado
- ESPERANDO: un hilo que está esperando que otro hilo realice una acción específica
- TIMED_WAITING: Esperando que el tiempo de ejecución de otro hilo alcance el tiempo especificado
- TERMINADO: el hilo sale de la ejecución
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/");
});
//观察线程状态
Thread.State state = thread.getState();
System.out.println(state); //New状态
thread.start();
state = thread.getState();
System.out.println(state);//Run状态
while (state!=Thread.State.TERMINATED){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
Hilo Cortés
El subproceso que se está ejecutando actualmente está suspendido, pero no se bloqueará. El
subproceso actual pierde el procesador y está listo para la programación.
Si la cortesía es exitosa depende de la CPU. Si la cortesía es exitosa, esperará la próxima programación.
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
Resultados del:
El hilo es forzado hasta el final
- Usar el método join ()
- El hilo que usa el método join () se verá obligado a ejecutarse hasta el final y no abandonará el procesador.
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("强制执行线程来了"+i);
}
}
public static void main(String[] args) throws Exception{
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 500; i++) {
if(i==200){
thread.join();
}
System.out.println("主线程"+i);
}
}
}
La vida es más que perseverancia y trabajo duro. Los sueños son búsquedas significativas.
Finalmente, les deseo éxito temprano en sus estudios, obtenga una oferta satisfactoria, obtenga un ascenso rápido y aumente su salario, y alcance la cima de la vida.
Si necesita software de código fuente de cursos y otros materiales, agregue un pequeño asistente vx: xcw18874131605 (nota: CSDN)