传统线程互斥

传统线程的互斥技术:

关键字:Synchronized

例子:

public class TraditionalThreadSynchronized {

  public static void main(String[] args) {
    new TraditionalThreadSynchronized().init();
  }

  private void init(){

    final Output output = new Output();

    new Thread(new Runnable(){

      @.....

      public void run(){

        while(true){

          try(){

            Thread.sleep(100);

          }catch(){

            e.printStrackTrace();

          }

          output.outputer("zhangsan");

        }

      }

    }).start();

 

    

    new Thread(new Runnable(){

      @.....

      public void run(){

        while(true){

          try(){

            Thread.sleep(100);

          }catch(){

            e.printStrackTrace();

          }

          output.outputer("zhangsan");

        }

      }

    }).start();

 

 

  }

  class Output{

    public void outputer(String name){

      int len = name.length();

      synchronized(this){

        for(int i = 0; i< len ; i ++){

          System.out.println(name.charAt(i));

        }

      }

      Syso();

    }

  }


}

 

//注:静态方法的锁是当前类的字节码。

posted on 2017-06-29 21:53  Deveo  阅读(145)  评论(0编辑  收藏  举报

导航