线程关键字:synchronized;作用:同步锁,使得线程有先后顺序。
public class Test {
public static void main(String[] args){
Account account = new Account(1000);
OperationThread oper1 = new OperationThread(account,500,"柜台");
OperationThread oper2 = new OperationThread(account,600,"ATM");
oper1.start();
oper2.start();
}
}
public class Account {
private int count;
public Account(int count){
this.count = count;
}
public int getCount(){
return count;
}
public synchronized int getCash(int cash){
if(cash>count){
return -1;
}else if(cash<count){
count = count-cash;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return cash;
}
}
public class OperationThread extends Thread{
private Account account;
private int cash;
private String OperationType;
public OperationThread(Account account,int cash,String OperationType){
this.account=account;
this.cash=cash;
this.OperationType=OperationType;
}
public void run(){
super.run();
int result = account.getCash(cash);
if(result==-1){
System.out.println(OperationType+"取现失败,账户余额为:"+account.getCount()+",准备取现的额度为:"+cash);
}else{
System.out.println(OperationType+"取现成功,账户余额为:"+account.getCount()+",准备取现的额度为:"+cash);
}
}
}
输出的结果:
ATM取现失败,账户余额为:500,准备取现的额度为:600
柜台取现成功,账户余额为:500,准备取现的额度为:500
柜台取现成功,账户余额为:500,准备取现的额度为:500
线程池;多个线程的存在,但是过多的线程严重消耗cpu,因此,
线程池里的每个线程需要重复利用,意味着建立线程池:
public static void main(String[] args) {
ThreadPool pool = new ThreadPool();
for(int i=0;i<60;i++){
MyTask task = new MyTask(i);
pool.excute(task);
}
run方法:
public static void main(String[] args) {
ThreadPool pool = new ThreadPool();
for(int i=0;i<60;i++){
MyTask task = new MyTask(i);
pool.excute(task);
}
public void run() {
while(true){
//同步关键字
synchronized (taskList) {
if(taskList.isEmpty()){
try {
taskList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//取出一个任务,并执行
MyTask task = taskList.remove(0);
System.out.println(this.getName()+"开始执行"+task.index+"任务");
task.work();
}
}
public void run() {
while(true){
//同步关键字
synchronized (taskList) {
if(taskList.isEmpty()){
try {
taskList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//取出一个任务,并执行
MyTask task = taskList.remove(0);
System.out.println(this.getName()+"开始执行"+task.index+"任务");
task.work();
}
}