首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么调试在处理多线程时不能正常工作?

为什么调试在处理多线程时不能正常工作?
EN

Stack Overflow用户
提问于 2016-08-09 07:03:40
回答 1查看 55关注 0票数 0

我有关于多线程编程的基本信息,所以我努力改进这个主题和工作调试模式,但它不能正常工作。

代码示例:

代码语言:javascript
复制
public class MultiThreadsExample implements Runnable {

private Thread t;
private String threadName;

//我有创建线程的构造函数方法

代码语言:javascript
复制
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.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-09 07:30:33

我想,从您的评论中,您希望有一个输出,如: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并发性的教程,比如这一个。他们解释了有关线程同步的一些基本知识。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38844185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档