package com.zhlk.thread;public class TraditionalThreadSync { /** * 创建日期:2017-3-4下午10:53:49 作者:lvguanghui */ public static void main(String[] args) { new TraditionalThreadSync().init(); } PRivate void init(){ final Outputer output=new Outputer(); new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } output.output3("lvguanghui"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } output.output1("lvjinhan"); } } }).start(); } static class Outputer { public synchronized void output1(String name) { int len = name.length(); //在方法内部使用关键字synchronized对代码块实现加锁 synchronized (Outputer.class) { for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } } public synchronized void output2(String name) { int len = name.length(); for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } //在方法中使用关键字synchronized实现加锁 public static synchronized void output3(String name) { int len = name.length(); for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } }}
新闻热点
疑难解答