==================================
需求:
銀行有一個金庫。
有兩個存戶分別存300,每次存100,存3次
目的:該程式是否有安全問題,如果有如何解決?
如何找問題:
1.明確哪些代碼是多線程運行代碼
2.明確共用資料
3.明確多線程運行代碼中哪些語句是操作共用資料
的。
解決前:
class Bank
{
//成員變數都是2
private int sum;
//這個也是1
public void add(int n)
{
//是3
sum=sum+n;
syso("sum="+sum);
}
}
class Cus implements Runnable
{
//是2
private Bank b=new Bank();
//下面也是1
public void run()
{
for(int x=0;x<3;x++)
{
//是3
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();
}
}
解決後:
class Bank
{
private int sum;
//Object obj =new Object();
public synchronized void add(int n)
{
//synchronized(obj){
sum=sum+n;
try{Thread.sleep(10);}catch
(Exception e){}
syso("sum="+sum);
//}
}
}
class Cus implements Runnable
{
private Bank b=new Bank();
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();
}
}
====================================
線程間通訊----代碼最佳化
接等待喚醒機制:
class Res{
private String name;
private String sex;
boolean flag=false;
public synchronized void set(String
name,String sex)
{
if(flag)
try{this.wait();}catch(){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out(){
if(!flag)
try{this.wait();}catch(){}
Syso(name+sex);
flag=falsh;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
//Object obj=new Object();
Input(Res r){
this.r=r;
}
public void run(){
int x=0;
while(true)
{
if(x==0){
r.set("XX","XX");
}else{
r.set("XX","XX");
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
//Object obj=new Object();
Onput(Res r){
this.r=r;
}
public void run(){
while(true)
{
r.out();
}
}
}
}
class InputOutputDemo
{
public static void main(String []
args)
{
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
/*
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();*/
}
}