public class Test1 implements Runnable{
public void run() {
synchronized(this){
System.out.println(System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(System.currentTimeMillis());
}
}
public static void main(String[] args){
Test1 test = new Test1();
for(int i=0 ; i<10 ; i++){
new Thread(test).start();
}
}
}
此例中执行的结果为1260782644968
1260782646968
1260782646968
1260782648968
1260782648968
1260782650984
1260782650984
1260782652984
1260782652984
1260782654984
1260782654984
1260782656984
1260782656984
1260782658984
1260782658984
1260782660984
1260782660984
1260782662984
1260782662984
1260782664984
可以看出有十个不同的进程先后执行,这是因为new Thread(test).start(),每次授权给进程执行的对象只有test,而一个对象一次只能授权给一个对象,所以十个进程先后执行了。
public class Test1 implements Runnable{
public void run() {
synchronized(this){
System.out.println(System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(System.currentTimeMillis());
}
}
public static void main(String[] args){
for(int i=0 ; i<10 ; i++){
new Thread(new Test()).start();
}
}
}
执行结果为
1260782849109
1260782849109
1260782849109
1260782849109
1260782849109
1260782849109
1260782849109
1260782849109
1260782849109
1260782849109
1260782851109
1260782851109
1260782851109
1260782851109
1260782851109
1260782851109
1260782851109
1260782851109
1260782851109
1260782851109
可以看出结果相同,这是因为每次授权的对象都不同,这样他们可以同时执行。