public class KK {
public static void main(String[] args){
Runnable r=new MO();
Thread t1=new Thread(r);
Thread t2=new Thread(r);
t1.start();
t2.start();
}
}
class MO implements Runnable{
public synchronized void run(){
for(int i=0;i<100;i++){
System.out.println(i);
}
}
}
结果是确定的
public class KKK {
public static void main(String[] args){
OO o1=new OO();
OO o2=new OO();
o1.start();
o2.start();
}
}
class OO extends Thread{
public synchronized void run(){
for(int i=0;i<100;i++){
System.out.println(i);
}
}
}
结果不确定,synchronized好像没起作用, 麻烦给个详细解释 先谢谢了//
public static void main(String[] args){
Runnable r=new MO();
Thread t1=new Thread(r);
Thread t2=new Thread(r);
t1.start();
t2.start();
}
}
class MO implements Runnable{
public synchronized void run(){
for(int i=0;i<100;i++){
System.out.println(i);
}
}
}
结果是确定的
public class KKK {
public static void main(String[] args){
OO o1=new OO();
OO o2=new OO();
o1.start();
o2.start();
}
}
class OO extends Thread{
public synchronized void run(){
for(int i=0;i<100;i++){
System.out.println(i);
}
}
}
结果不确定,synchronized好像没起作用, 麻烦给个详细解释 先谢谢了//
创建了2个线程,每个线程调用的是同一MO对象的run方法,因为run方法是synchronized,所以这2个线程先后独占式执行run方法,最后的结果该是2次串行的。第二个:
创建了2个线程,每个线程各自调用一个OO对象的run方法,此时run方法是否synchronized已经无关紧要了,最后的结果该是并行的了。