Java 线程同步(synchronized)

使用synchronized关键字可实现线程的互斥功能,即在此关键字包围的代码块中逻辑必须都执行完后才能再次此块,就像加了一把锁,执行到此块后此块就被锁住,其他逻辑不能再调用。但要实现同步必须对同一个对象加锁,否则无效。如:

public class Synchronized {

	public static void main(String[] args) {
		final Outputer outputer = new Outputer();
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					outputer.output("ThreadA");
				}
			}
		}).start();
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					outputer.output("ThreadB");
				}
			}
		}).start();
	}

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

		public void output2(String arg) {
			synchronized (this) {

				for (int i = 0; i < arg.length(); i++) {
					System.out.print(arg.charAt(i));
				}
				System.out.println();
			}
		}

		public void output3(String arg) {
			synchronized (Synchronized.class) {

				for (int i = 0; i < arg.length(); i++) {
					System.out.print(arg.charAt(i));
				}
				System.out.println();
			}
		}
		
		public void output4(String arg) {
			synchronized (arg) {

				for (int i = 0; i < arg.length(); i++) {
					System.out.print(arg.charAt(i));
				}
				System.out.println();
			}
		}
	}
}
在主线程中新开两个线程,如果调用Outputer类中的output4方法打印,则无法同步,因为两个arg参数不是通个对象。

第一个和第三个方法可实现同步,因为都是给Outputer这个类本身加锁。


如下两个方法也可实现互斥同步,因为都是对Outputer类的实例对象加锁:

		public  synchronized void output(String arg) {
			for (int i = 0; i < arg.length(); i++) {
				System.out.print(arg.charAt(i));
			}
			System.out.println();
		}

		public void output2(String arg) {
			synchronized (this) {
				for (int i = 0; i < arg.length(); i++) {
					System.out.print(arg.charAt(i));
				}
				System.out.println();
			}
		}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值