java - 多线程后无法获得正确的执行时间

标签 java multithreading

为什么我不能得到正确的输出? 这是我的代码:

=======

1.主要内容

public class ThreadDebut {
  public static void main(String args[]) {
     PrintDemo PD = new PrintDemo();
     List<ThreadDemo> th = new ArrayList<ThreadDemo>();
     ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
     ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );


     T1.start();
     th.add(T1);
     T2.start();
     th.add(T2);

     for(ThreadDemo t : th) {
         try {
            t.join();
         }catch( Exception e) {
           System.out.println("Interrupted");
         }
     }
   System.out.println("\n\n\n");
   }
}

2.线程和方法

 class PrintDemo {
   public void printCount() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
         }
      }catch (Exception e) {
         System.out.println("Thread  interrupted.");
      }
   }
}

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;

       ThreadDemo( String name,  PrintDemo pd) {
      threadName = name;
          PD = pd;
       }

       public void run() {
          synchronized(PD) {
             PD.printCount();
          }
          System.out.println("Thread " +  threadName + " exiting.");
       }

   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

我的意思是我想在两个线程执行完毕后得到这个System.out.println("\n\n\n");。但是,在线程 1 的同步之前,我得到的只是随机的。我已经执行了 thread.join() 但失败了。为什么?请有人向我解释一下...谢谢并问候!!!

最佳答案

您正在尝试同时子类化和使用委托(delegate)。您本质上为每个线程创建两个线程。您应该重写 Thread 的方法,而不是使用委托(delegate)。就像这样:

static class ThreadDemo extends Thread {
    private String threadName;
    PrintDemo PD;

    ThreadDemo (String name, PrintDemo pd) {
        threadName = name;
        PD = pd;
    }

    @Override
    public void run() {
        synchronized (PD) {
            PD.printCount();
        }
        System.out.println("Thread " + threadName + " exiting.");
    }

    @Override
    public void start() {
        System.out.println("Starting " + threadName);
    }
}

关于java - 多线程后无法获得正确的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41744283/

相关文章:

java - URL.openStream 很慢

java - 将图像从网站加载到 Android 应用程序

c++ - Qt:这段代码中的QBuffer线程安全吗?

c++ - 通过 Berkeley 套接字使用线程通知

Java多线程同步

java - 将工作线程与主线程一起使用会减少基于 Java 的智能设备的响应延迟或增加工作负载吗?

java - 如何在运行时更改 dozer XML 中的某些文本?

java - JTextArea 中插入符号位置下方的工具提示

java - 无法在模拟器和设备上加载 Android Mapview Activity

c# - 访问另一个线程中的方法返回的值