线程的同步互斥synchronized

IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结!


注意:

   1.静态方法所使用的同步监视器对象是该类的字节码对象,如:Outputer.class

   2.类非静态方法所使用的同步监视器对象时this,即类本实例对象

   3.synchronized实现两个线程的synchronized代码块的内容不会被中断。保证synchronized代码块的原子性。


例子程序:

package edu.review;

public class TraditionalThreadSynchronized {

	/**
	 * 结果:当Outputer的同一对象的两方法被两线程调用,是否会同步
	 *                output1()   output2()   output3()   output4() 
	 *   output1()     同步         同步       不同步      不同步
	 *   output2()                  同步       不同步      不同步
	 *   output3()                              同步        同步
	 *   output4()                                          同步
	 **/
	public static void main(String[] args) {
       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.output1("zhangxiaoxiang");
				}
			}
		}).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.output4("lihuoming");
 				}
 			}
 		}).start();

	}
   
	static class Outputer{
		public synchronized void output1(String name){
		   for (int i = 0; i < name.length(); i++) {
			  System.out.print(name.charAt(i));
		   }
		   System.out.println();
		}
		
		public void output2(String name){
			synchronized(this){
			   for (int i = 0; i < name.length(); i++) {
				  System.out.print(name.charAt(i));
			   }
			   System.out.println();
			}
		}
		public static synchronized void output3(String name){
			   for (int i = 0; i < name.length(); i++) {
				  System.out.print(name.charAt(i));
			   }
			   System.out.println();
		}
		public void output4(String name){
			synchronized(Outputer.class){
			   for (int i = 0; i < name.length(); i++) {
				  System.out.print(name.charAt(i));
			   }
			   System.out.println();
			}
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值