简体   繁体   English

尝试使用Threads实现一个简单的java程序

[英]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. 从上面的代码中,我如何在run()方法中实现这样的逻辑:如果线程等待超过指定的时间,我想杀死该线程并检查正在运行的其他两个线程会发生什么。 When I execute the above code it gives the following output. 当我执行上面的代码时,它给出了以下输出。

State of Thread-1: TERMINATED 线程状态-1:终止
State of Thread-2 RUNNABLE 线程状态-2 RUNNABLE
State of Thread-3 RUNNABLE 线程状态-3 RUNNABLE
isalive:false 的IsAlive:假
isalive:true 的IsAlive:真
isalive:true 的IsAlive:真
Thread-2 is sleeping for 151 线程-2正在睡眠151
Thread-3 is sleeping for 384 线程-3正在睡眠384
Thread-2 is done. 线程2完成。
Thread-3 is done. 线程3完成。

First thread.stop() should not be used as it is deprecated. 应该使用第一个thread.stop()因为它已被弃用。 ( Read here why ) (请阅读此处原因

Secondly consider using ExecutorService.submit to execute a thread; 其次考虑使用ExecutorService.submit来执行一个线程; 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. 在这个future对象上,您可以在手动等待所需的时间限制后直接调用cancel或者在间隔到期后使用TimeoutException终止之前调用get需要等待的时间,可以取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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