首页 > 编程 > Java > 正文

java多线程加锁

2019-11-06 07:25:28
字体:
来源:转载
供稿:网友
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();			 		}	}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表