同步函数使用的是哪一个锁呢?
函数需要被对象调用,那么函数都有一个所属对象引用,就是this。。
通过验证,发现不在是this,因为静态方法中不可以定义this。
静态进内存:内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 该类对象的类型是Class
函数需要被对象调用,那么函数都有一个所属对象引用,就是this。。
所以同步函数使用的锁是this。
代码:
class Demo implements Runnable
{
private int t=200;
Object obj = new Object();
boolean flag = true;
public void run () {
if(flag) {//同步代码块
while(true) {
synchronized (this) {
if(t>0) {
try {Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+"-code:"+t--);
}
}
}
}
else {//同步函数
while(true)
show();
}
}
public synchronized void show() {//this
if(t>0) {
try {Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+"--show:"+t--);
}
}
}
public class code
{
public static void main(String[] args) {
Demo t = new Demo();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {Thread.sleep(10);} catch (Exception e) {}
t.flag = false;
t2.start();
}
}
如果同步函数被静态修饰后,使用的锁是什么呢?
通过验证,发现不在是this,因为静态方法中不可以定义this。
静态进内存:内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 该类对象的类型是Class
静态的同步方法:使用的锁是该方法所在类的字节码文件对象。 类名.class 字节码文件对象是唯一的。
用static修饰->对象在方法区中
不用static修饰->对象在堆内存中
代码:
class Demo implements Runnable
{
private static int t=200;
boolean flag = true;
public void run () {
if(flag) {
while(true) {
synchronized (Demo.class) {
if(t>0) {
try {Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+"-code:"+t--);
}
}
}
}
else {
while(true)
show();
}
}
public static synchronized void show() {//class
if(t>0) {
try {Thread.sleep(10);} catch (Exception e) {}
System.out.println(Thread.currentThread().getName()+"--show:"+t--);
}
}
}
public class code
{
public static void main(String[] args) {
Demo t = new Demo();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {Thread.sleep(10);} catch (Exception e) {}
t.flag = false;
t2.start();
}
}
死锁:同步中嵌套同步,锁不同。
Jion:当线程执行到了B线程的 .join()方法时,A就会等待。等B线程都执行完,A才会执行。
join可以用来临时加入线程执行。