请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php
锁:保护资源—-资源:卫生间、线程:上卫生间的人、锁:卫生间的门
一把锁只有一把钥匙
只有执行完被锁住的程序块钥匙才能被释放
锁保护谁:成员属性/静态成员属性
锁有几种:this—-当前对象的锁
package thread;
public class Thread_6 {
/**
* @param args
*/
public static void main(String[] args) {
final Method m = new Method();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
m.m1();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
m.m2();
}
});
t1.start();
t2.start();
}
}
class Method{
public void m1(){
synchronized (this) {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
public void m2(){
synchronized (this) {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
}
类.class—-当前类的class对象的锁
成员属性
方法上加锁—-锁就是this对象的锁
静态方法加锁—-class实例的锁
锁属于谁:
锁是属于对象的
每一个对象都有一把唯一的锁
package thread;
public class Thread_5 {
/**
* @param args
*/
public static void main(String[] args) {
SaleTask sale = new SaleTask();
Thread t1 = new Thread(sale);
t1.setName("网络");
Thread t2 = new Thread(sale);
t2.setName("电话");
Thread t3 = new Thread(sale);
t3.setName("现场");
t1.start();
t2.start();
t3.start();
}
}
class SaleTask implements Runnable{
int id = 100;
@Override
public void run() {
while(true){
synchronized (this) {//t1,t2,t3拿到钥匙,且只有一把钥匙
if(id>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("卖票"+id--);
}else{
System.out.println("票卖完");
break;
}
}//运行到这里归还钥匙
}
}
}