java线程同步<二>

 
为了解决 线程安全问题,也就是多个线程访问同一个实例变量,而引入了同步的概念

不加同步的代码块

package com.xxg.reflect;

public class Test3 {

	
	public static void main(String[] args) {

		CSD cs = new CSD();
		Thread th1 = new Thread(cs);
		Thread th2 = new Thread(cs);
		th1.start();
		th2.start();
		


	}

}
class  CSD implements Runnable{

	public int  a ;
	public void run() {
					
		
		  a++;
		 try {
			Thread.sleep(1000);
			System.out.println("【当前线程】-----"+Thread.currentThread().getName()+"----a---"+a);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		}
	

	
}
//===============================测试结果=======================

【当前线程】-----Thread-0----a---2
【当前线程】-----Thread-1----a---2



从上面结果看,在第一个线程执行run()方法时,进入sleep()后,第二个线程修改了实例变量所以打印的结果都为2

加了同步方法的代码块:



package com.xxg.reflect;

public class Test3 {

	
	public static void main(String[] args) {

		CSD cs = new CSD();
		Thread th1 = new Thread(cs);
		Thread th2 = new Thread(cs);
		th1.start();
		th2.start();
		


	}

}
class  CSD implements Runnable{

	public int  a ;
	public void run() {
		synchronized (this) {
			
		
		  a++;
		 try {
			Thread.sleep(1000);
			System.out.println("【当前线程】-----"+Thread.currentThread().getName()+"----a---"+a);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		}
	}
	
	
}
//========================测试结果================================
【当前线程】-----Thread-0----a---1
【当前线程】-----Thread-1----a---2



解释:加上synchronized后:表示当前线程获得该对象锁了,其他线程无法进入锁定区域,直到当前线程执行完该方法体,释放对象才能

你可能感兴趣的:(java线程)