有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    我不确定你是如何实现你的代码的,所以我只是在这里猜测

    一种方法是跟踪你的线索

    例如,创建地图:

    Map<String,Thread> threads=new HashMap<String,Thread>();// ensure each Thread has a unique id, in this case its supposedly a String. then you can control them from outside your thread pool.
    

    以下是一个被黑客攻击的实现:

    public class hello{
    
    public static void main(String...strings )throws Exception{
    
         ExecutorService executor = Executors.newFixedThreadPool(5);
         Map<String,Thread> threads=new HashMap<String, Thread>();
         for(int i=0;i<5;i++){
             Thread t = new myRunnable((i+1) +" ");
             threads.put((i+1)+"", t);
             executor.execute(t);
         }
    
         Thread.sleep(2000);
        ((myRunnable)threads.get("1")).isSuspened=true;
    }
    
    private static class myRunnable extends Thread{
        String a;
        public  boolean isSuspened=false;
    
        public myRunnable(String a) {
            this.a=a;
            // TODO Auto-generated constructor stub
        }
        @Override
        public void run(){
            while(true){
                if(isSuspened){
                    continue;
                }
                try{
                    System.out.println(a);
                    Thread.sleep(2000);
                }catch(Exception e){}
            }
        }
    }
    }