我有关于多线程编程的基本信息,所以我努力改进这个主题并运行调试模式,但它无法正常工作。
代码示例:
public class MultiThreadsExample implements Runnable {
private Thread t;
private String threadName;
//我有构造方法创建线程
public static void main(String[] args) {
MultiThreadsExample thread1=new MultiThreadsExample("Thread-1");
thread1.start();
MultiThreadsExample thread2=new MultiThreadsExample("Thread-2");
thread2.start();
}
//runnable interface override method
@Override
public void run() {
System.out.println("Running thread name:" + threadName);
for (int i = 0; i < 4; i++) {
System.out.println("Working thread: " + i + " " + threadName);
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
Logger.getLogger(MultiThreadsExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Thread " + threadName + " interrupted.");
}
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
输出:
Creating thread name:Thread-1
Starting Thread-1
Creating thread name:Thread-2
Starting Thread-2
Running thread name:Thread-1
Working thread: 0 Thread-1
Working thread: 1 Thread-1
Working thread: 2 Thread-1
Working thread: 3 Thread-1
Thread Thread-1 interrupted.
Running thread name:Thread-2
Working thread: 0 Thread-2
Working thread: 1 Thread-2
Working thread: 2 Thread-2
Working thread: 3 Thread-2
Thread Thread-2 interrupted.
答案 0 :(得分:1)
从我的评论中我想,您希望得到如下输出:
Working thread: 0 Thread-1
Working thread: 0 Thread-2
Working thread: 1 Thread-1
Working thread: 1 Thread-2
...
这不是线程的工作方式。您无法控制完全执行线程的顺序。
它取决于JVM,并且非常依赖于您的机器和操作系统之类的东西,因为您甚至可以调试IDE。
因此,我可以告诉您的代码应该如此工作。
顺便说一下,当我运行你的代码时,这是输出,所以它可以在我的机器上运行:
Creating thread name: Thread-1
Starting Thread-1
Creating thread name: Thread-2
Starting Thread-2
Running thread name:Thread-1
Running thread name:Thread-2
Working thread: 0 Thread-1
Working thread: 0 Thread-2
Working thread: 1 Thread-1
Working thread: 1 Thread-2
Working thread: 2 Thread-1
Working thread: 2 Thread-2
Working thread: 3 Thread-1
Working thread: 3 Thread-2
Thread Thread-1 interrupted.
Thread Thread-2 interrupted.
你应该查看一些关于Java的并发性教程,如this one。 他们解释了一些关于线程同步的基础知识。