我該如何確保我的代碼使用了多線程機制?第一個代碼看起來像不使用多線程機制。爲什麼第二代碼的結果是無序?如何確認我的java使用多線程機制運行
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
好,我改變了代碼,如圖below.Just加上「我」來區分。
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
Java具有多線程,並且該功能有效。 – Raedwald 2014-10-22 08:18:03
是的,我正在學習java的多線程。我只想知道爲什麼我的第一個代碼的結果看起來像沒有多線程一樣? – wuyuanyi 2014-10-22 08:22:16
檢查[Java 101:瞭解Java線程,](http://www.javaworld.com/article/2074217/java-concurrency/java-101-understanding-java-threads--part-1--introducing-threads -and-runnables.html)。請注意,您的計算機每秒可執行大約1毫升的操作。嘗試添加** Thread.sleep(10); **到方法並增加發生率> 20 – 2014-10-22 08:25:23