/**
* 1.利用线程的两种创建方式,来创建线程: ① 线程 打印 1-100; ②线程 打印 A-Z 打印50 遍
*
* 并发打印。
*
*
* 2.用加对象锁的方式,写一个同步的银行取款案例。
*
* 3.银行取款的案例,用继承的方式实现,并且消除同步问题。
*
*/
public class Text {
public static void main(String[] args) {
1
//AThread at=new AThread();
//at.start();
//BThread bt=new BThread();
//Thread btt=new Thread(bt);
//btt.start();
2
//Bank b=new Bank();
//Thread t=new Thread(b);
//Thread t1=new Thread(b);
//t.setName("张三");
//t1.setName("李四");
//t.start();
//t1.start();
//3
Bank3 b=new Bank3();
Acc ac=new Acc(b);
Acc1 ac1=new Acc1(b);
ac.setName("张三");
ac1.setName("李四");
ac.start();
ac1.start();
}
}
class AThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 101; i++) {
System.out.println(i);
}
}
}
class BThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 51; i++) {
for (int j = 0; j < 26; j++) {
System.out.println((char)(65+j));
}
}
}
}
//2
class Bank implements Runnable{
double balance=1000;
Object o=new Object();
@Override
public synchronized void run() {
// TODO Auto-generated method stub
if(balance>0)
{
try {
Thread.sleep(10);
}catch(InterruptedException e) {
e.printStackTrace();
}
balance-=1000;
System.out.println(Thread.currentThread().getName()+"取款后,余额为"+balance);
}else {
System.out.println(Thread.currentThread().getName()+"余额不足");
}
}
}
//3
class Bank3{
public double balance=1000;
public synchronized void withdrow()
{
if(balance>0)
{
try {
Thread.sleep(10);
}catch(InterruptedException e) {
e.printStackTrace();
}
balance-=1000;
System.out.println(Thread.currentThread().getName()+"取款后,余额为"+balance);
}else {
System.out.println(Thread.currentThread().getName()+"余额不足");
}
}
}
class Acc extends Thread{
public Bank3 b;
public Acc(Bank3 b) {
// TODO Auto-generated constructor stub
this.b=b;
}
@Override
public void run() {
// TODO Auto-generated method stub
b.withdrow();
}
}
class Acc1 extends Thread{
public Bank3 b;
public Acc1(Bank3 b) {
// TODO Auto-generated constructor stub
this.b=b;
}
@Override
public void run() {
// TODO Auto-generated method stub
b.withdrow();
}
}