有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的多线程实现

我目前正在做一个项目,我必须使用线程。这是我第一次使用。所以我的代码有很多问题

首先,我尝试测试我的线程块是否同时工作

这是我的测试申请

public class sad extends Thread
{
private String name;

private Thread t1 = new Thread()
{
    @Override
    public void run()
    {
        while ( true )
        {
            System.out.println( "I am thread 1 and working properly" );
        }
    }
};
private Thread t2 = new Thread()
{
    @Override
    public void run()
    {
        while ( true )
        {
            System.out.println( "I am thread 2 and working properly" );
        }
    }
};

public void starter()
{
    t1.start();
    t2.start();
}
}

按钮部分:

btnNewButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent arg0) 
        {
            sadObj.starter();
        }
    });

当我运行这个程序时:

I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 1 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly
I am thread 2 and working properly

这是输出的有限版本。通常有很多输出,并且所有输出都是独立的。我的意思是,他们必须工作,他们必须打印混合。在我的例子中,他们一个接一个地行动

在我的项目中,我必须同时完成两项完全不同的任务。为了实现这一点,我更喜欢使用2线程对象。但我认为它们的运行时间并不完全相同,或者其中一个会因为某种原因而等待。两者都必须连续运行。我的实现是错的,还是怎么能做到

当我在java中搜索线程时,我发现如果计算机CPU有超过1个内核,多线程将非常有效。我的CPU是i7-3740M。我想它至少有4个内核。那么问题是什么呢

谢谢! 致意


共 (1) 个答案

  1. # 1 楼答案

    一般来说,内核通过在单个任务之间快速切换来模拟同时做几件事

    您的系统似乎在优化工作,选择不做太多切换,允许一个任务多次运行,另一个任务多次运行。这样它就不会频繁切换(这是一件昂贵的事情),一个线程的“运行”会跟在另一个线程的“运行”之后

    您可以向系统提供一个“提示”,表明您可以在特定点让位于另一个线程。它可能会为CPU提供更多切换线程的借口

    private Thread t1 = new Thread()
    {
        @Override
        public void run()
        {
            while ( true )
            {
                System.out.println( "I am thread 1 and working properly" );
                this.yield();
            }
        }
    };
    private Thread t2 = new Thread()
    {
        @Override
        public void run()
        {
            while ( true )
            {
                System.out.println( "I am thread 2 and working properly" );
                this.yield();
            }
        }
    };
    

    但归根结底,线程调度是你无法完全控制的事情

    另外,sad类不需要扩展线程,除非它有自己的run()方法并已启动。在你的例子中,情况并非如此