package duo_xian_cheng;
class dui_xiang extends Thread{
String name_1;
dui_xiang(String a ){
super();
name_1=a;
}
synchronized void fun_1(){
try{for(int i=0;i<10;i++)
{System.out.println(name_1+ "fun_1");
sleep(1000);}
}catch(InterruptedException e){
System.out.println( "InterruptedException:fun_1");
}
System.out.println( name_1+"fun_1");
}
synchronized void fun_2(){
try{for(int i=0;i<10;i++)
{System.out.println(name_1+ "fun_2");
sleep(1000);}
}catch(InterruptedException e){
System.out.println( "InterruptedException:fun_2");
}System.out.println( name_1+"fun_2");
}
synchronized void fun_3(){
try{for(int i=0;i<10;i++)
{System.out.println(name_1+ "fun_3");
sleep(1000);}
}catch(InterruptedException e){
System.out.println( "InterruptedException:fun_3");
}System.out.println( name_1+"fun_3");
}
public synchronized void run(){
fun_1();
fun_2();
fun_3();
}
}
public class dan_dui_xiang {
public static void main(String[] args) {
Thread a=new dui_xiang("线程1");
Thread b=new dui_xiang("线程2");
a.start();
b.start();
}
}
Thread a=new dui_xiang("线程1");
Thread b=new dui_xiang("线程2");
a.start();
b.start();
这里的synchronized 只对调用同一个类实例的方法有同步,你这是两个类实例,a,b,所以不起作用
同步原理是多个线程之间持有一个互斥锁,在单线程情况下是没有关系的。
只有拥有对互斥锁的竞争,你的synchronized才会有效果。
也就是说你的程序根本就没有并发...