---
title: "多线程--同步函数的使用"
author: "wststar"
date: "2012-05-21T17:55:08Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-05-21T17:55:08Z"
id: 1536516
url: "https://wststar.iteye.com/blog/1536516"
---

/\**

多线程--同步函数的使用

银行账户 两个储户  每人存300 每次100  存三次

\*/

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){

}

System.out.println("sum="+sum);

//}

}

} 

class Cus implements Runnable

{

private Bank b = new Bank();

public void run(){

for(int i = 0 ; i &lt; 3 ; i ++){

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();

}

}