举例说明线程中sleep方法的使用。

解决方案 »

  1.   

    public class TestSync{
    public static void main(String args[]){
    Target t=new Target();
    new ThreadA(t).start();
    new ThreadB(t).start();
    }
    }class Target{
    String msg="<我是线程要访问的对象>";
    public void show(){
    char []msgchars=msg.toCharArray();
    for(int i=0;i<msgchars.length;i++){
    System.out.print(msgchars[i]);
    try{
    Thread.sleep(1000);
    }catch(Exception e){
    }
    }
    }
    }class ThreadA extends Thread{
    Target target;
    public ThreadA(Target target){
    this.target=target;
    }
    public void run(){
    synchronized(target){// 同步对象
    target.show();
    }
    }
    }
    class ThreadB extends Thread{
    Target target;
    public ThreadB(Target target){
    this.target=target;
    }
    public void run(){
    synchronized(target){// 同步对象
    target.show();
    }
    }
    }
      

  2.   

    public class TestSync{
    public static void main(String args[]){
    Target t=new Target();
    new ThreadA(t).start();
    new ThreadB(t).start();
    }
    }class Target{
    String msg="<我是线程要访问的对象>";
    public synchronized void show(){
    char []msgchars=msg.toCharArray();
    for(int i=0;i<msgchars.length;i++){
    System.out.print(msgchars[i]);
    try{
    Thread.sleep(1000);
    }catch(Exception e){
    }
    }
    }
    }class ThreadA extends Thread{
    Target target;
    public ThreadA(Target target){
    this.target=target;
    }
    public void run(){
    target.show();
    }
    }
    class ThreadB extends Thread{
    Target target;
    public ThreadB(Target target){
    this.target=target;
    }
    public void run(){
    target.show();
    }
    }