-2
編寫一個從1到10的線程,另一個從1到10的線程。create-two-threads-both -display-numbers-one
對於例如:線程1輸出:1 線程2輸出:1 線程1輸出:2 線程2輸出:2
我已經寫下面代碼
public class Test1 extends Thread
{
public void run(){
for(int i=1;i<=10;i++){
//System.out.println(i);
try{
System.out.println(Thread.currentThread().getName()+"+i);
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 t1=new Test1();
Test1 t2=new Test1();
//Test1 t3=new Test1();
t1.start();
t2.start();
//t3.start();
}
}
Got the output as:-
Thread-1 1
Thread-0 1
Thread-1 2
Thread-0 2
Thread-0 3
Thread-1 3
Thread-0 4
Thread-1 4
Thread-1 5
Thread-0 5
Thread-1 6
Thread-0 6
Thread-1 7
Thread-0 7
Thread-1 8
Thread-0 8
Thread-1 9
Thread-0 9
Thread-1 10
Thread-0 10
但輸出不序列 我想輸出爲: 線程1輸出:1 線程2輸出:1 線程1輸出:2 線程2輸出:2
我新的線程concept.Could你幫我實現同步,從而使線程將一個到最後後序打印一個 –