public void run() {
for (int x = 0; x < 3; x++) {
b.add(100);
}
}
}
class BankDemo {
public static void main(String[] args) {
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
6.同步的锁
6.1函数需要被对象调用,那么函数都有一个所属对象引用,就是this.,所以同步函数使用的锁是this
6.2.静态函数的锁是class对象
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象,类名.class,该对象的类型是Class
6.3.静态的同步方法,使用的锁是该方法所在类���字节码文件对象,类名.class
/*
* 需求:简易买票程序,多个窗口同时卖票
*/
public class Ticket implements Runnable {
private static int tick = 100;
Object obj = new Object();
boolean flag=true;
public void run() {
if(flag){
while (true) {
synchronized (Ticket.class) {
if (tick > 0) {
System.out.println(Thread.currentThread().getName()
+ "code:" + tick--);
}
}
}
}else{
while(true){
show();
}
}
}
public static synchronized void show() {
if (tick > 0) {
System.out.println(Thread.currentThread().getName() + "show:"
+ tick--);
}
}
}
class ThisLockDemo {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
t.flag=false;
Thread t2 = new Thread(t);
//Thread t3 = new Thread(t);
//Thread t4 = new Thread(t);
t1.start();
t2.start();
//t3.start();
//t4.start();
}
}
7.多线程,单例模式-懒汉式
懒汉式与饿汉式的区别:懒汉式能延迟实例的加载,如果多线程访问时,懒汉式会出现安全问题,可以使用同步来解决,用同步函数和同步代码都可以,但是比较低效,用双重判断的形式能解决低效的问题,加同步的时候使用的锁是该类锁属的字节码文件对象
/*
* 单例模式
*/
//饿汉式
public class Single {
private static final Single s=new Single();
private Single(){}
public static Single getInstance(){
return s;
}
}
//懒汉式
class Single2{
private static Single2 s2=null;
private Single2(){}
public static Single2 getInstance(){
if(s2==null){
synchronized(Single2.class){
if(s2==null){
s2=new Single2();
}
}
}
return s2;
}
}
class SingleDemo{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
8.多线程-死锁
同步中嵌套同步会出现死锁
/*
* 需求:简易买票程序,多个窗口同时卖票
*/
public class DeadTest implements Runnable {
private boolean flag;
DeadTest(boolean flag) {
this.flag = flag;
}