千锋逆战班:孙华建
在千锋学习第28天
“未来的你会感谢今天奋斗的自己”
今天我学习了java课程,多线程,线程安全
#中国加油!武汉加油!千锋加油!也为自己加油!!!#…
笔记:
课堂案例:
public class TestSynchronized {
public static void main(String[] args) {
//临界资源,被共享的对象
//临界资源对象只有一把锁
Account acc = new Account("6002","1234",2000);
//两个线程对象共享同一个银行卡资源
Thread husband = new Thread(new Husband(acc),"丈夫");
Thread wife = new Thread(new Wife(acc),"妻子");
husband.start();
wife.start();
}
}
class Husband implements Runnable{
Account acc;
public Husband(Account acc){
this.acc = acc;
}
//线程任务:取款
public void run() {
this.acc.widthdrawal("6002", "1234", 1200);//原子操作
}
}
class Wife implements Runnable{
Account acc;
public Wife(Account acc){
this.acc = acc;
}
//线程任务:取款
public void run() {
this.acc.widthdrawal("6002", "1234", 1200);//原子操作
}
}
//银行账户,银行卡
class Account{
String cardNo;
String password;
double balance;
public Account(String cardNo, String password, double balance) {
super();
this.cardNo = cardNo;
this.password = password;
this.balance = balance;
}
//取款(原子操作。从插卡成功到取款成功的一系列步骤,不可缺少)
public void widthdrawal(String no,String pwd,double money){
synchronized(this){//对当前共享实例加锁
System.out.println(Thread.currentThread().getName()+"正在读卡。。。");
if(no.equals(this.cardNo)&&pwd.equals(this.password)){
System.out.println(Thread.currentThread().getName()+"验证成功。。。");
if(money <= this.balance){
try {
Thread.sleep(1000);//模拟现实世界,ATM机数钱
} catch (InterruptedException e) {
e.printStackTrace();
}
this.balance = this.balance-money;
System.out.println(Thread.currentThread().getName()+"取款成功!当前余额为:"+this.balance);
}else{
System.out.println(Thread.currentThread().getName()+"当前卡内余额不足");
}
}else{
System.out.println(Thread.currentThread().getName()+"卡号或密码错误");
}
}
}
}
宏观并行,微观串行。cpu会分配给不同的进程时间片,一个进程时间片结束执行下一个,多个进程穿插执行,但由于穿插切换时间只有几纳秒,人眼是很难观察到的。
C
C
A
public class TestThread {
public static void main(String[] args) {
Num t1 = new Num();
t1.start();
Letters letters = new Letters();
Thread t2 = new Thread(letters);
t2.start();
}
}
class Num extends Thread{
public void run(){
for(int i = 1;i <= 100;i++){
System.out.println(i+":"+"1~26");
}
}
}
class Letters implements Runnable{
public void run(){
for(int i = 1;i <= 100;i++){
System.out.println(i+":"+"A~Z");
}
}
}
程序为共享资源加锁,保证每一个进程的原子操作不被破坏;
如果不加的话,会出现两个程序并发访问临界资源,导致原子结构被破坏有可能出现数据异常
C