正确结束java中的线程

时间:2012-05-14 12:22:35

标签: java multithreading

我在Java中遇到Threads问题。 我想编写一个程序,其中有Class Main,它有一些类的ThreadList(Class Task),它只写一个字母和数字。 Object Main只是从ArrayList中唤醒一个Thread,让它在同一个对象(Main)睡眠另一个时执行某些操作。 但是有一个问题,即使我将Main.ACTIVE更改为false也没有结束所有线程的一些保留,并且它是随机的,我只是想让它们结束并写:

我说的是goodbay + character - 就像那样

public class Main extends Thread {
    ArrayList<Thread> threads;
    static boolean ACTIVE = true;
    public Main() {
        super();
        threads = new ArrayList<Thread>();
    }

    public void run(){

        Object monitor = new Object();
        for (int i = 0; i <= 5; i++) {
            threads.add(new Thread(new Task(i + 65, monitor)));
        }

        long cT = System.currentTimeMillis();
        for (int i = 0; i < threads.size(); i++) {
            threads.get(i).start();
        }
        System.out.println("BEFORE synchronized(monitor)");
        synchronized(monitor){
            while (System.currentTimeMillis() - cT < 1000) {
                try{
                    monitor.notify();
                    Thread.sleep(50);
                    monitor.wait();
                } catch(Exception e){
                    e.printStackTrace();}
                }
                System.out.println("BEFORE ACTIVE= FALSE and after WHILE in Main");
                ACTIVE = false;
                for(int i  = 0; i < threads.size(); i++){
                    System.out.println(threads.get(i).getState());
                }
            }
            System.out.println("LAST COMMAND IN MAIN");
        }
    }

    public static void main(String[] args) {
        new Main().start();
        //new Thread(new Task(65)).start();
    }
}

任务类

public class Task implements Runnable {
    int nr;
    char character;
    Object monitor;

    public Task(int literaASCII, Object monitor) {
        this.nr = 0;
        this.monitor = monitor;
        character = (char) (literaASCII);
    }

    @Override
    public void run() {
        synchronized (monitor) {
            while (Main.ACTIVE) {
                try {
                     System.out.println("ENTERING WHILE IN TASK");
                    monitor.wait();
                    System.out.print(nr + "" + character + ", ");
                    nr++;
                    int r = (int) ((Math.random() * 50) + 50); // <500ms,1000ms)
                    Thread.sleep(r);
                } catch (Exception e) {e.printStackTrace();}
                monitor.notify();
                 System.out.println("YYYYYYYYY");
            }
             System.out.println("AFTER WHILE IN Task");
        }
        System.out.println("I am saying goodbye " + character);
    }
}

3 个答案:

答案 0 :(得分:4)

我建议您查看java.util.concurrent包中更现代的并发类,尤其是ExecutorService。并阅读“Java Concurrency In Practice。”

答案 1 :(得分:3)

您的问题适用于ACTIVE应标记为volatile的初学者。多个线程共享的任何变量都需要以某种方式synchronized或标记为volatile,以便在读写时有一个内存屏障。

从布尔角度来看,您可以做的另一件事是使用AtomicBoolean类而不是volatile boolean

而不是static volatile boolean,您可以考虑为每个volatile boolean对象设置一个Task,以便Main对各个任务进行更细粒度的控制正在使用static“全局”变量。您甚至可以添加task.shutdown()方法来设置活动标记。

最后,正如@duffmo所提到的,如果你总是想要运行一个线程,你应该总是考虑使用其中一个线程池ExecutorService。像Executors.newFixedThreadPool(1)这样的东西。但我无法确定你是否只想要一个线程。如果您使用ExecutorService,那么main就会:

ExecutorService threadPool = Executors.newFixedThreadPool(1);
List<Future> futures = new ArrayList<Future>();
for (int i = 0; i <= 5; i++) {
    // the monitor would not be needed
    threadPool.submit(new Task(i + 65));
}
threadPool.shutdown();
for (Future future : futures) {
    // this waits for the working task to finish
    future.get();
}

但是如果你需要你的后台任务停止并开始像目前使用monitor一样,那么这个模型可能不起作用。

答案 2 :(得分:0)

现在是

0A,0B,0C,0D,0E,0F,1A,1B,1C,1D,1E,1F,WAITING 等候 等候 等候 等候 等候 最后一个主要指令

我在启动线程后添加了睡眠

import java.util.ArrayList;

public class Main extends Thread {
ArrayList<Thread> threads;
volatile static boolean ACTIVE = true;
public Main() {
    super();
    threads = new ArrayList<Thread>();
}

 public void run(){

Object monitor = new Object();
for (int i = 0; i <= 5; i++) {
  threads.add(new Thread(new Task(i + 65, monitor)));
}

long cT = System.currentTimeMillis();
for (int i = 0; i < threads.size(); i++) {
  threads.get(i).start();
}
try{Thread.sleep(50);}catch(Exception e){e.printStackTrace();}
 //   System.out.println("BEFORE synchronized(monitor)");
synchronized(monitor){
  while (System.currentTimeMillis() - cT < 1000) {
      try{

    monitor.notify();
    Thread.sleep(500);

    monitor.wait();}catch(Exception e){e.printStackTrace();}
  }
   //    System.out.println("BEFORE ACTIVE= FALSE and after WHILE in Main");
  ACTIVE = false;
  for(int i  = 0; i < threads.size(); i++){
      System.out.println(threads.get(i).getState());
  }


}
System.out.println("LAST COMMAND IN MAIN");

  }


  public static void main(String[] args) {
     new Main().start();
    //new Thread(new Task(65)).start();

}

}

和TASK

public class Task implements Runnable {
int nr;
char character;
Object monitor;

public Task(int literaASCII, Object monitor) {
    this.nr = 0;
    this.monitor = monitor;
    character = (char) (literaASCII);
}

@Override
public void run() {
    synchronized (monitor) {
        while (Main.ACTIVE) {
            try {
//               System.out.println("ENTERING WHILE IN TASK");
                monitor.wait();
                System.out.print(nr + "" + character + ", ");
                nr++;
                int r = (int) ((Math.random() * 50) + 50); // <500ms,1000ms)

                Thread.sleep(r);
            } catch (Exception e) {e.printStackTrace();}
            monitor.notify();
    //       System.out.println("YYYYYYYYY");
        }
         System.out.println("AFTER WHILE IN Task");
    }
    System.out.println("I am saying goodbye " + character);
}

}