小弟对线程这块一直不甚理解 在网上找的例子也都不是很理想 请各位高手给分别给个例子 最好能详细解释下 谢谢

解决方案 »

  1.   

    class Callme {
    synchronized public void call(String msg) {
    System.out.print("[" + msg);
     try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("]");
    }
    }class Caller implements Runnable { Thread t; private Callme callme; private String msg; public Caller(Callme callme, String msg) {
    this.callme = callme;
    this.msg = msg;
    t = new Thread(this);
    t.start();
    } public void run() {
    callme.call(this.msg);
    }
    }public class SynchronizedDemo { public static void main(String[] args) throws InterruptedException {
    Callme c = new Callme();
    new Caller(c, "Hello");
    new Caller(c, "World");
    new Caller(c, "!");
    }
    }
      

  2.   

    这个例子里
    如果call方法没有同步,那么两个线程可能同时去执行call方法
    你把call方法前面的synchronized去掉试试