java - Java中三个线程的合并

标签 java multithreading

我试图在 java 中创建几个流,我的程序必须创建 3 个线程和 1 个主线程,然后停止。

我创建了一个实现了 Runnable 的类

class NewThread implements Runnable {
String name;
Thread t;

NewThread(String threadname){
    name = threadname;
    t = new Thread (this, name);
    System.out.println(t);
    t.start();
}

public void run (){
    try {
        System.out.println("111");// why cant see it?
        Thread.sleep(1000);
    }
    catch (InterruptedException e){
        System.out.println(e);
    }
    System.out.println("End Thread");
}

主要:

 public class ThreadDemo {
 public static void main (String []args){
    new Thread ("F");
    new Thread ("S");
    new Thread ("T");
    
    try {
        Thread.sleep(10000);
    }
    catch (InterruptedException e){
        
    }
    System.out.println("End M");
}
}

我想我会得到像 3 个字符串 111 和一个字符串 End M -

111
111
111
End M

但我只是

 End M

谁能告诉我为什么我的程序结果没有得到 3 个字符串?

最佳答案

您需要创建 NewThread 实例而不是通用 Threads 来执行代码:

new NewThread("F");
...

关于java - Java中三个线程的合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15209462/

相关文章:

java - 让套接字等待来自 JTextArea 的输入

java - 计算一个数的幂;重复的话

c# - 使用 switch 和枚举代替命名方法

java - Quartz 作业已完成但线程仍处于阻塞状态

c# - StructureMap 中的跨线程冲突

java - 为什么我不能在 MessageDigest 实例上调用 .update

java - 如何将字符串动态转换为其他类型java

c++ - OpenMP:从上到下的文本

objective-c - 如何包装异步类使其同步?使用 NSRunLoop?

c++ - 每个线程都有自己的堆栈吗?