我是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<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] array = threadSet.toArray(new Thread[threadSet.size()]);
for(int i=0;i<array.length;i++){
// System.out.println(array[i].getName());
if(array[i].getName().equals(threadName)){
_tmp=array[i];
}
}
return _tmp;
}
}
public static void main(String args[]) {
TripThread myThread = new TripThread ();
myThread.start();
}
}
提前致谢.....
答案 0 :(得分:0)
这里你的Thread t没有工作要做,所以只需通过更改你的构造函数来指定它(通过覆盖run方法)。
ThreadBehaviour() {
t = new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("running");
} catch (Exception ex) {
Thread.currentThread().interrupt();
}
}
}
};
t.setName("hello");
}
答案 1 :(得分:0)
根据上述评论中的要求,示例线程应该如下所示。
public class SampleThreadRunner
{
public static void main(String [] args){
SampleThread sampleThread1 = new SampleThread("Thread1");
SampleThread sampleThread2 = new SampleThread("Thread2");
Thread thread1 = new Thread(sampleThread1);
Thread thread2 = new Thread(sampleThread2);
thread1.start();
thread2.start();
}
}
class SampleThread implements Runnable{
private String threadName;
private int counter;
public SampleThread(String threadName){
this.threadName = threadName;
}
public void run()
{
while(counter < 1000){
System.out.println("Printing " + threadName + " Count: " + counter++);
}
}
}
或者像之前的回答一样。
P.S:没有时间创建一个Git Repo链接样本,可能会在晚上这样做。答案 2 :(得分:0)
Thread thread = new Thread("Thread Name") {
public void run() {
while(true){
//your code
}
}
};
thread.start();
答案 3 :(得分:0)
类DigitalClock扩展了线程 {
public void run()
{
try {
Thread.sleep(5000);
LocalDateTime todayDateTime = LocalDateTime.now();
System.out.println(todayDateTime);
Thread t=new DigitalClock();
t.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
公共类App4 { / ** * @参数args * / 公共静态void main(String [] args){ // TODO自动生成的方法存根 线程t = new DigitalClock(); t.isDaemon(); t.setPriority(4); t.start(); } }