多线程的锁,安全问题

a 当多条语句在操做同一个线程共享数据时,一个线程对多条语句的执行只执行了一部分,另外一个线程就参与进来执行,致使了共享数据错误;咱们就须要的是让正在执行的线程执行完了再让其余线程执行;面试

b  同步的前提:1必需要有2个或2个以上的线程函数

                    二、必须是同一个线程使用同一个锁this

c   业务逻辑写在run()里面,给线程起名字;spa

1:   同步代码块:synchronized(对象) {//里面能够放类的字节码对象或者对象,其实锁是是资源线程

须要被同步代码code

}对象

package DuoThread;

class Test implements Runnable {
	private int tick = 100;
	
	public void run() {
		while(true) {
			synchronized(Test.class) {
				if(tick > 0) {
					try {
						Thread.sleep(10);
					}catch (Exception e){}
					System.out.println(Thread.currentThread().getName() + "...." + tick--);
				}
			}
		}
	}
}
public class Ticket2 {

	public static void main(String[] args) {
		Test t = new Test();
		Thread t1 =new Thread(t);
		Thread t2 =new Thread(t);
		Thread t3 =new Thread(t);
		Thread t4 =new Thread(t);

		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}

4个线程交替出票内存

2: 同步函数     (synchronized放在方法的void以前),非static的方法锁是this,static方法的锁是类的字节码对象(xxx.class)资源

package DuoThread;

class Test implements Runnable {
	private int tick = 100;
	
	public synchronized void run() {
		while(true) {
			//synchronized(Test.class) {
				if(tick > 0) {
					try {
						Thread.sleep(10);
					}catch (Exception e){}
					System.out.println(Thread.currentThread().getName() + "...." + tick--);
				}
			//}
		}
	}
}
public class Ticket2 {

	public static void main(String[] args) {
		Test t = new Test();
		Thread t1 =new Thread(t);
		Thread t2 =new Thread(t);
		Thread t3 =new Thread(t);
		Thread t4 =new Thread(t);

		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}

只有一个线程在执行,由于一个线程执行了,其余线程就进不去get

3.面试题: 3.1 2个同步方法,一个static,一个非static,他们能够一块儿被访问,由于static在内存中只有一份,锁的力度不一样

                3.2 2个同步方法,不能同时访问,由于他们都要获取对象,会发生互斥

总之,就是看他们锁的是否是同一个资源;

相关文章
相关标签/搜索