-1

我对 Java 中的线程有疑问。我想编写一个程序,其中有一个类 Main,它有一些类(类任务)的线程的 ArrayList,它只写一个字母和数字。Object Main 只是从 ArrayList 中唤醒一个线程,并让它在同一个对象(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);
    }
}
4

3 回答 3

4

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

于 2012-05-14T12:24:35.367 回答
3

您的问题是针对ACTIVE应标记为的初学者volatile。任何由多个线程共享的变量都需要以某种方式进行synchronized标记或标记,volatile以便在其读写周围具有内存屏障。

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

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

最后,正如@duffmo 提到的,ExecutorService如果您总是只想让一个线程运行,您应该始终考虑使用其中一个线程池。类似的东西Executors.newFixedThreadPool(1)。但是我不能完全确定您是否一直只想要一个线程。如果您使用 an ExecutorServicethenmain就可以了:

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那么此模型可能无法正常工作。

于 2012-05-14T12:24:27.993 回答
0

现在纳斯维尔是

0A, 0B, 0C, 0D, 0E, 0F, 1A, 1B, 1C, 1D, 1E, 1F, 等待等待等待等待等待等待等待最后一个命令在主

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

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();

}

}

和任务

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);
}

}

于 2012-05-15T00:30:13.093 回答