传统synchronized互斥技术 发表于 2018-02-22 | 分类于 juc 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677package cn.itcast.heima2;public class TraditionalThreadSynchronized { /** * @param args */ public static void main(String[] args) { new TraditionalThreadSynchronized().init(); } private void init(){//todo 如果在不使用outputer时,是线程不安全的,打印时会出现串行的情况 final Outputer outputer = new Outputer(); new Thread(new Runnable(){ @Override public void run() { while(true){ try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputer.output("zhangxiaoxiang");//todo 与下面的比较 } } }).start(); new Thread(new Runnable(){ @Override public void run() { while(true){ try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputer.output2("lihuoming");//todo 与上面的比较 } } }).start(); } static class Outputer{ public void output(String name){ int len = name.length(); synchronized (this) //todo 代码块的锁闩为Outputer.class时可以和方法3互斥,在this的情况下只能和方法2互斥 { for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); } } public synchronized void output2(String name){ //todo 方法 int len = name.length(); for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); } public static synchronized void output3(String name){ //todo 静态方法 int len = name.length(); for(int i=0;i<len;i++){ System.out.print(name.charAt(i)); } System.out.println(); } }}