0
我有另一個類中的arrayList的打印函數。每當我調用它時,它只顯示一個空的ArrayList。我究竟做錯了什麼?我幾乎模擬使用線程的電梯,只是將樓層添加到arrayList,然後需要對它們進行排序。我只是想打印數組來看看它是否有序。從另一個類打印ArrayList
import java.util.Random;
import java.util.concurrent.Semaphore;
public class Threads {
public static int RandomFloor(){
Random random = new Random();
int floor = random.nextInt(6) + 2;
return floor;
}
public static void main(String[] args) throws Exception {
Semaphore sem = new Semaphore(0);
//Random number for floors
Elevator elevator1 = new Elevator();
//Creates the first set of threads and assigns the floor using random number generator defined at the top.
Thread myThread1 = new Thread(new Driver(1,RandomFloor()));
Thread myThread2 = new Thread(new Driver(2,RandomFloor()));
Thread myThread3 = new Thread(new Driver(3,RandomFloor()));
Thread myThread4 = new Thread(new Driver(4,RandomFloor()));
Thread myThread5 = new Thread(new Driver(5,RandomFloor()));
Thread myThread6 = new Thread(new Driver(6,RandomFloor()));
Thread myThread7 = new Thread(new Driver(7,RandomFloor()));
Thread elevator = new Thread(new Elevator());
//Start first set of threads
myThread1.start();
myThread1.join();
myThread2.start();
myThread3.start();
myThread4.start();
myThread5.start();
myThread6.start();
myThread7.start();
elevator1.printFloors();
sem.acquire();
}
}
其中包含ArrayList和打印功能電梯類
import java.util.*;
public class Elevator implements Runnable
{
List<Integer> floors = new ArrayList<Integer>();
int floor;
//add floors into Arraylist
public void addFloors(int floor)
{
this.floor=floor;
floors.add(floor);
System.out.println("Added to floor array\n");
System.out.println(floors);
}
public void run()
{
}
public void sortFloors()
{
Collections.sort(floors);
}
public void printFloors()
{
//System.out.println(floors);
}
}
您是否注意到您的'printFloors'方法此刻不做任何事情? – Henry
你在哪裏調用'addFloors'? – 4castle
你知道每次'新的電梯'運行它創建一個新的電梯,對吧? – immibis