1
多个线程宏观并行,微观串行。
2
C
3
C
4
A
5
public class TestT5 {
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(new MyRunnable());
MyThread t1 = new MyThread();
t1.start();
t0.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
for(int i = 0; i < 100; i++){
for(int j = 1; j < 27; j++){
System.out.println(j);
}
}
}
}
class MyThread extends Thread{
@Override
public void run() {
for(int i = 0; i < 100; i++){
for(int j = 97; j < 123; j++){
System.out.println((char)j);
}
}
}
}
6
- 上锁作用,使同一lock下进程不竞争。
- 若不加synchronized则两进程互相竞争,打印交错。
7
C
随堂案例
package day3_11;
public class TestSyn {
public static void main(String[] args) {
Account account = new Account("family", "123456", 2000);
Thread t0 = new Thread(new Husband(account), "Husband");
Thread t1 = new Thread(new Wife(account), "Wife");
t0.start();
t1.start();
}
}
class Husband implements Runnable{
Account account;
public Husband(Account account) {
super();
this.account = account;
}
@Override
public void run() {
this.account.withdrawal(account.name, account.code, 1000);
}
}
class Wife implements Runnable{
Account account;
public Wife(Account account) {
super();
this.account = account;
}
@Override
public void run() {
this.account.withdrawal(account.name, account.code, 1100);
}
}
class Account{
String name;
String code;
double balance;
public Account(String name, String code, double balance) {
super();
this.name = name;
this.code = code;
this.balance = balance;
}
public void withdrawal(String name, String code, double money){
synchronized (this) {
System.out.println("读卡中...");
if(name.equals(this.name) && code.equals(this.code)){
System.out.println(Thread.currentThread().getName()+"验证成功。。。");
if(money <= balance){
balance = balance - money;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "成功取款" + money + "当前余额" + balance);
}else{
System.out.println(Thread.currentThread().getName() + "存款不足");
}
}else{
System.out.println(Thread.currentThread().getName() + "用户名或密码错误");
}
}
}
}
笔记
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/21d7cf70963b7920da492720ae437ad7.png)