简体   繁体   中英

Trying to implement a simple java program using Threads

import java.util.Random;

public class ThreadLogic implements Runnable {
    private String name;
    private int time;
    private Random rand = new Random();

    public ThreadLogic(String name) {
        this.name = name;
        this.time = rand.nextInt(1000);


    }

    public void run() {
        try {
            System.out.printf("%s is sleeping for %d \n", this.name, this.time);
            Thread.sleep(this.time);
             System.out.printf("%s is done.\n", this.name);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

        public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadLogic("Thread-1"));
        Thread t2 = new Thread(new ThreadLogic("Thread-2"));
        Thread t3 = new Thread(new ThreadLogic("Thread-3"));

       t1.start();
       //t1.stop();
       t2.start();
       t3.start();
       t1.stop();
       System.out.println("State of Thread-1:"+" "+t1.getState());
       System.out.println("State of Thread-2"+" "+t2.getState());
       System.out.println("State of Thread-3"+"  "+t3.getState());
       System.out.println("isalive:"+t1.isAlive());
       System.out.println("isalive:"+t2.isAlive());
       System.out.println("isalive:"+t3.isAlive()); 

       }
    }

From the above code, how can I implement such logic in run() method: if the thread is waiting for more than the specified time I want to kill that thread and check what happens to the other two threads that are running. When I execute the above code it gives the following output.

State of Thread-1: TERMINATED
State of Thread-2 RUNNABLE
State of Thread-3 RUNNABLE
isalive:false
isalive:true
isalive:true
Thread-2 is sleeping for 151
Thread-3 is sleeping for 384
Thread-2 is done.
Thread-3 is done.

First thread.stop() should not be used as it is deprecated. ( Read here why )

Secondly consider using ExecutorService.submit to execute a thread; which will return a Future . On this future object you can either directly invoke cancel after manually waiting for desired time limit OR invoke get which take the time to wait before terminating with a TimeoutException after interval expires, post which you could cancel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM