/**
* 如果同步函数诶静态函数修饰后,使用的所是什么呢?
* 通过验证:发现不是this
*/
package java160108;
/**
* @author LiZheng
*
*/
public class StaticMethodDemo {
/**
* @param args
*/
public static void main(String[] args) {
Ticket4 ticket = new Ticket4();
Thread thread1 = new Thread(ticket);
Thread thread2 = new Thread(ticket);
// Thread thread3 = new Thread(ticket);
// Thread thread4 = new Thread(ticket);
thread1.start();
try {
Thread.sleep(10);//10毫秒
} catch (Exception e) {
e.printStackTrace();
}
ticket.flag=false;
thread2.start();
}
}
//要注意同步的代码是那一部分
//同步函数用的当前对象
class Ticket4 implements Runnable {
private static int tick = 1000;
Object obj = new Object();
boolean flag=true;
@Override
public void run() {
if (flag) {
while (true) {
// synchronized同步代码块的关键字,参考火车卫生间是否有人
synchronized (Ticket4.class) {
if (tick>0) {
try {
// 此处会引发多线程的问题
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...code..." + tick--);
}
}
// show();//this.show();
}
}else {
while (true) {
show();
}
}
}
public static synchronized void show() {
if (tick > 0) {
try {
// 此处会引发多线程的问题
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...show..." + tick--);
}
}
}
* 如果同步函数诶静态函数修饰后,使用的所是什么呢?
* 通过验证:发现不是this
*/
package java160108;
/**
* @author LiZheng
*
*/
public class StaticMethodDemo {
/**
* @param args
*/
public static void main(String[] args) {
Ticket4 ticket = new Ticket4();
Thread thread1 = new Thread(ticket);
Thread thread2 = new Thread(ticket);
// Thread thread3 = new Thread(ticket);
// Thread thread4 = new Thread(ticket);
thread1.start();
try {
Thread.sleep(10);//10毫秒
} catch (Exception e) {
e.printStackTrace();
}
ticket.flag=false;
thread2.start();
}
}
//要注意同步的代码是那一部分
//同步函数用的当前对象
class Ticket4 implements Runnable {
private static int tick = 1000;
Object obj = new Object();
boolean flag=true;
@Override
public void run() {
if (flag) {
while (true) {
// synchronized同步代码块的关键字,参考火车卫生间是否有人
synchronized (Ticket4.class) {
if (tick>0) {
try {
// 此处会引发多线程的问题
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...code..." + tick--);
}
}
// show();//this.show();
}
}else {
while (true) {
show();
}
}
}
public static synchronized void show() {
if (tick > 0) {
try {
// 此处会引发多线程的问题
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...show..." + tick--);
}
}
}