当前位置: 代码迷 >> J2SE >> JAVA 多线程的 有关问题
  详细解决方案

JAVA 多线程的 有关问题

热度:289   发布时间:2016-04-24 18:06:32.0
JAVA 多线程的 问题、
Java code
import java.util.*;public class Syncduixiang implements Runnable{    int b=1000;    public static void main(String []args) throws Exception{        Syncduixiang ss=new Syncduixiang();        Thread s1=new Thread(ss);        System.out.println(new Date());                s1.start();                ss.m2();        System.out.println("b="+ss.b+new Date());    }    public void run(){        try{            m1();        }catch(Exception e){                    }    }    public synchronized void m1 ()throws Exception{        System.out.println("m1先执行");        int a=3000;        Thread.sleep(5000);        System.out.println("m1a="+a+new Date());    }    public synchronized void m2 ()throws Exception{        System.out.println("m2先执行");        b=4000;        Thread.sleep(2000);        System.out.println("m2b="+b+new Date());    }    }

运行结果是
Tue Sep 13 20:29:20 CST 2011
m2先执行
m2b=4000Tue Sep 13 20:29:22 CST 2011
b=4000Tue Sep 13 20:29:22 CST 2011
m1先执行
m1a=3000Tue Sep 13 20:29:27 CST 2011

为什么m1和m2 之间会阻塞 他们之间没冲突啊

------解决方案--------------------
synchronized 把那个对象的方法锁住了,同一个对象只能同时调用一个,所以造成阻塞。
------解决方案--------------------
这个是两个对象在两个线程调用的。。。
第一个对象 Ff f1=new Ff(); 调用的m2
第二个对象 Ff f2=new Ff(); 调用的m1

你可以尝试
Java code
import java.util.*;public class Syncduixiang extends Thread{    int b=1000;     Ff f1=new Ff();    public static void main(String []args) throws Exception{        Syncduixiang ss=new Syncduixiang();              System.out.println(new Date());                ss.start();               ss.f1.m2();        System.out.println("b="+ss.b+new Date());    }    public void run(){        try{                     f1.m1();        }catch(Exception e){                    }    }        }class Ff{    public synchronized void m1 ()throws Exception{        System.out.println("m1先执行");        int a=3000;        Thread.sleep(3000);        System.out.println("m1a="+a+new Date());    }    public synchronized void m2 ()throws Exception{        System.out.println("m2先执行");        Syncduixiang q=new Syncduixiang();        q.b=4000;        Thread.sleep(2000);        System.out.println("m2b="+q.b+new Date());    }}
  相关解决方案