예제 #1
0
  public static void selfTest() {
    final Lock lock = new Lock();

    final Condition2 empty = new Condition2(lock);
    final LinkedList<Integer> list = new LinkedList<>();

    KThread consumer =
        new KThread(
            new Runnable() {
              public void run() {
                lock.acquire();
                while (list.isEmpty()) {
                  empty.sleep();
                }
                Lib.assertTrue(list.size() == 5, "List should have 5 values.");
                while (!list.isEmpty()) {
                  System.out.println("Removed " + list.removeFirst());
                }
                lock.release();
              }
            });

    KThread producer =
        new KThread(
            new Runnable() {
              public void run() {
                lock.acquire();
                for (int i = 0; i < 5; i++) {
                  list.add(i);
                  System.out.println("Added " + i);
                }
                empty.wake();
                lock.release();
              }
            });

    consumer.setName("Consumer");
    producer.setName("Producer");
    consumer.fork();
    producer.fork();
    consumer.join();
    producer.join();
  }
예제 #2
0
파일: KThread.java 프로젝트: kjyang/cs120f
  /**
   * Create the idle thread. Whenever there are no threads ready to be run, and
   * <tt>runNextThread()</tt> is called, it will run the idle thread. The idle thread must never
   * block, and it will only be allowed to run when all other threads are blocked.
   *
   * <p>Note that <tt>ready()</tt> never adds the idle thread to the ready set.
   */
  private static void createIdleThread() {
    Lib.assertTrue(idleThread == null);

    idleThread =
        new KThread(
            new Runnable() {
              public void run() {
                while (true) yield();
              }
            });
    idleThread.setName("idle");

    Machine.autoGrader().setIdleThread(idleThread);

    idleThread.fork();
  }