a 当多条语句在操作同一个线程共享数据时,一个线程对多条语句的执行只执行了一部分,另一个线程就参与进来执行,导致了共享数据错误;我们就需要的是让正在执行的线程执行完了再让其他线程执行;
b 同步的前提:1必须要有2个或2个以上的线程
2、必须是同一个线程使用同一个锁
c 业务逻辑写在run()里面,给线程起名字;
1: 同步代码块:synchronized(对象) {//里面可以放类的字节码对象或者对象,其实锁是是资源
需要被同步代码
}
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();
}
}
只有一个线程在执行,因为一个线程执行了,其他线程就进不去
3.面试题: 3.1 2个同步方法,一个static,一个非static,他们可以一起被访问,因为static在内存中只有一份,锁的力度不同
3.2 2个同步方法,不能同时访问,因为他们都要获取对象,会发生互斥
总之,就是看他们锁的是不是同一个资源;