Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用多线程机制确认java运行_Java_Multithreading - Fatal编程技术网

如何使用多线程机制确认java运行

如何使用多线程机制确认java运行,java,multithreading,Java,Multithreading,如何确保我的代码使用了多线程机制?第一个代码看起来像没有使用多线程机制。为什么第二个代码的结果是无序的 public class ThreadDemo9_2 { public static void main(String[] args) { TestThread t = new TestThread() ; new Thread(t).start(); for(int i =0;i < 5;i++) {

如何确保我的代码使用了多线程机制?第一个代码看起来像没有使用多线程机制。为什么第二个代码的结果是无序的

public class ThreadDemo9_2
{
    public static void main(String[] args)
    {
        TestThread t = new TestThread() ;
        new Thread(t).start();
        for(int i =0;i < 5;i++)
        {
            System.out.println("main thread is running");
        }
    }
}
class TestThread implements Runnable
{
    public void run()
    {
        for(int i =0;i<5;i++)
        {
            System.out.println("test thread is running");
        }
    }
}
我改变了代码,如下所示。只需添加“I”来区分

public class ThreadDemo9_2
{
    public static void main(String[] args)
    {
        TestThread t = new TestThread() ;
        new Thread(t).start();
        for(int i =0;i < 5;i++)
        {
            System.out.println(i+"main thread is running");
        }
    }
}
class TestThread implements Runnable
{
    public void run()
    {
        for(int i =0;i<5;i++)
        {
            System.out.println(i+"test thread is running");
        }
    }
}

如果线程之间没有任何进一步的同步来互相阻塞/等待,则无法预测其中一个线程何时运行以及运行多长时间


如果在第一个示例中循环几百次,您将看到输出也是“无序”的

Java有多线程功能,这项功能很有效。是的,我正在学习Java的多线程功能。我只是想知道为什么我的第一个代码的结果似乎与没有多线程的结果相同?请检查。请注意,您的计算机每秒可以执行大约1mln操作。尝试添加Thread.sleep(10);在我的第一个例子中,我已经循环了300次,但它仍然是有序的
public class ThreadDemo9_2
{
    public static void main(String[] args)
    {
        TestThread t = new TestThread() ;
        new Thread(t).start();
        for(int i =0;i < 5;i++)
        {
            System.out.println(i+"main thread is running");
        }
    }
}
class TestThread implements Runnable
{
    public void run()
    {
        for(int i =0;i<5;i++)
        {
            System.out.println(i+"test thread is running");
        }
    }
}
0main thread is running
0test thread is running
1main thread is running
1test thread is running
2main thread is running
2test thread is running
3main thread is running
4main thread is running
3test thread is running
4test thread is running