java 中多线程的同步函数的运用

/*
* 需求:
* 银行有一个金库
* 有两个储户,分别存300元。每次存100 , 存三次
*
* 这个是有线程问题的,
*
* 我们应该通过下边的三个方法来查找问题
* 1.明确哪些代码是多线程运行的代码
* 2.明确共享数据
* 3.明确多线程运行代码中哪些是操作共享数据的
*/ class Bank
{
private int sum;
public synchronized void add (int n)
{
sum = sum + n;
try {Thread.sleep (10);}catch (Exception e){}
System.out.println ("sum="+ sum);
}
} class Cus implements Runnable
{
private Bank bank = new Bank ();
public void run(){
for (int x=0; x<3;x++){
bank.add(100); } }
}
public class BankDemo { public static void main(String[] args) { Cus cus = new Cus ();
Thread t1 = new Thread (cus);
Thread t2 = new Thread (cus);
t1.start();
t2.start(); } }

上边代码中的synchorinized 关键字 是可以放到函数前边的,这就叫做同步函数 跟下边的用法是一个作用

Object obj = new Object ();

Synchronized (obj) {

//需要同步的代码块

}

上边的代码的例子中的锁使用的对象其实就是自己本身this,在多线程操作中为了让线程安全,必须使用同一把锁

如果同步函数被static 修饰,那么就不是this了 因为静态方法中没有this 方法

静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象,叫做类名.class 该对象的类型是Class

静态的同步方法是 使用的锁是该方法坐在类的字节码文件对象。类名.class

l例如

 class Ticket implements Runnable
{
private static int tick = 100;
boolean flag = true;
Object obj = new Object();
public void run (){ if (flag){
while (true){ synchronized(Ticket.class){
if (tick > 0){
try {
Thread.sleep (10);
}
catch (Exception a)
{ }
System.out.println(Thread.currentThread().getName()+"sale:"+tick--);
}
} }
}else
while (true)
show();
}
public static synchronized void show()
{ if (tick > 0){
try {
Thread.sleep (10);
}
catch (Exception a)
{ }
System.out.println(Thread.currentThread().getName()+"sale:"+tick--);
}
}
} public class ThreadDemo { public static void main(String[] args) {
// TODO Auto-generated method stub Ticket t = new Ticket ();
Thread t1 = new Thread (t);
Thread t2 = new Thread (t);
// Thread t3 = new Thread (t);
// Thread t4 = new Thread (t);
t1.start();
t2.start();
// t3.start();
// t4.start(); } }
上一篇:如何在插件中添加Actor类


下一篇:[转]ms sql 2000 下批量 附加/分离 数据库(sql语句)