---
title: "java synchronized 功能 清晰 解释"
author: "msnvip"
date: "2008-12-16T10:41:51Z"
tags: []
slug: "java-synchronized"
draft: false
lastmod: "2008-12-16T10:41:51Z"
id: 294891
url: "https://msnvip.iteye.com/blog/294891"
---

关键字synchronized  的理解

1.锁定当前对象;

2.保证当前对象中 **所有** 有 synchronized 标志的方法 同一时间 只能有一个线程访问

3.对当前对象中,没有synchronized标志的方法,没有限制

-----------------------------------------------------------------

```java

public class LockTest {
	public synchronized void say(){
		Thread t = Thread.currentThread();
		System.out.println("say is call by " + t);
	}
	public synchronized void say1(){
		
		Thread t = Thread.currentThread();
		System.out.println("say1 is call by " + t);
		try {
			t.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println("say1 is call by " + t);
		System.out.println("say1 " + t + "执行完毕");
	} 
	public synchronized void say2(){
		Thread t = Thread.currentThread();
		try {
			t.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("say2 is call by " + t);
		System.out.println("say2 " + t + "执行完毕");
	}
}
```



```java

public class Test {
	private static  LockTest lockTest = new LockTest();
	private static Thread test1;
	private static Thread test2;
	public static void main(String[] args) {
		
		Test test = new Test();
		test.ini();
		
		test1.start();
		test2.start();
		lockTest.say();
//		lockTest.say1();
//		lockTest.say2();
	}
	private void ini(){
		test1 = new Thread(new RunTest1());
		test2 = new Thread(new RunTest2());
		
	}
	private class RunTest1 implements Runnable{

		@Override
		public void run() {
			System.out.println("线程0开始启动");
			lockTest.say1();
		}
		
	}
	private class RunTest2 implements Runnable{

		@Override
		public void run() {
			System.out.println("线程1开始启动");
			lockTest.say2();
		}
		
	}
}


```


-------------------------------------------------------------
运行结果:
say is call by Thread
线程1开始启动
线程0开始启动
say2 is call by Thread
say2 Thread执行完毕
say1 is call by Thread
say1 Thread执行完毕

因cpu分配给线程 时间片,不是每次运行结果都一样(mian,thread0,thread1的顺序)
单不会出现say1, say2 或 线程0,线程1 嵌套执行的情况