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

时间:2014-10-22 08:12:52

标签: 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++)
        {
            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");
        }
    }
}

前面代码的结果如下

main thread is running
main thread is running
main thread is running
main thread is running
main thread is running
test thread is running
test thread is running
test thread is running
test thread is running
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");
        }
    }
}

结果是:

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

1 个答案:

答案 0 :(得分:1)

如果没有任何进一步的线程同步来阻塞/等待对方,你就无法预测你的一个线程何时有时间运行以及持续多长时间。

如果你在第一个例子中循环几百次,你会看到输出是&#34;无序&#34;同样。