Программисты JAVA общаются здесь
Anonymous
Как непрерывно запускать поток в Java
Сообщение
Anonymous » 06 май 2026, 18:06
Я новичок в Java, я хочу, чтобы поток выполнялся непрерывно, прежде чем я хочу проверить, означает ли уже работающий тот же поток остановку и запуск снова. Пожалуйста, помогите мне!
Вот мой код:
Код: Выделить всё
public class TripTrackService {
private static class TripThread implements Runnable {
private final Thread t;
TripThread() {
t = new Thread ();
t.setName("hello");
}
public void start() {
if( !t.isAlive())
{
t.start();
System.out.println(t.getName()+ " Running....."+t.isAlive());
Thread th = getThreadByName("hello");
if(th!=null)
System.out.println(th.getName()+"Already Running....."+th.isAlive());
else
System.out.println("No thread Found");
}
else{
System.out.println("Already Running.....");
Thread th = getThreadByName("test");
if(th!=null){
System.out.println(th.getName()+"Else Already Running....."+th.isAlive());
th.interrupt();
}
else{
System.out.println("No thread Found");
}
}
}
public void stop() {
if(t.isAlive())
t.stop();
}
public void run() {
if(!t.isAlive())
t.run();
}
public Thread getThreadByName(String threadName){
Thread _tmp = null;
Set threadSet = Thread.getAllStackTraces().keySet();
Thread[] array = threadSet.toArray(new Thread[threadSet.size()]);
for(int i=0;i
1778080005
Anonymous
Я новичок в Java, я хочу, чтобы поток выполнялся непрерывно, прежде чем я хочу проверить, означает ли уже работающий тот же поток остановку и запуск снова. Пожалуйста, помогите мне! Вот мой код: [code]public class TripTrackService { private static class TripThread implements Runnable { private final Thread t; TripThread() { t = new Thread (); t.setName("hello"); } public void start() { if( !t.isAlive()) { t.start(); System.out.println(t.getName()+ " Running....."+t.isAlive()); Thread th = getThreadByName("hello"); if(th!=null) System.out.println(th.getName()+"Already Running....."+th.isAlive()); else System.out.println("No thread Found"); } else{ System.out.println("Already Running....."); Thread th = getThreadByName("test"); if(th!=null){ System.out.println(th.getName()+"Else Already Running....."+th.isAlive()); th.interrupt(); } else{ System.out.println("No thread Found"); } } } public void stop() { if(t.isAlive()) t.stop(); } public void run() { if(!t.isAlive()) t.run(); } public Thread getThreadByName(String threadName){ Thread _tmp = null; Set threadSet = Thread.getAllStackTraces().keySet(); Thread[] array = threadSet.toArray(new Thread[threadSet.size()]); for(int i=0;i