一、同步代码块
synchronized(synObject) (synObject可以是类实例,也可以是类)
每一个对象或者类都对应着一个锁。synchronized块中的代码必须获得对象synObject的锁才能执行。当一个线程欲进入该对象的同步代码块时,JVM将检查对象的锁是否被其他线程获得,如果没有,则JVM把该对象的锁交给当前请求锁的线程,该对象获得锁后就可以进入关键代码区域执行。
二、代码实现
package org.Thread;
public class ThreadDemo03
{
public static void main(String[] args)
{
User u = new User("张三",100);
MyThread t1 = new MyThread("线程A",u,20);
MyThread t2 = new MyThread("线程B",u,-60);
MyThread t3 = new MyThread("线程C",u,-80);
MyThread t4 = new MyThread("线程D",u,-30);
MyThread t5 = new MyThread("线程E",u,32);
MyThread t6 = new MyThread("线程F",u,21);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class MyThread extends Thread
{
private User u;
private int y = 0;
MyThread(String name,User u,int y)
{
super(name);
this.u = u;
this.y = y;
}
public void run()
{
u.oper(y);
}
}
class User
{
private String code;
private int cash;
User(String code,int cash)
{
this.code = code;
this.cash = cash;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public void oper(int x)
{
try{
Thread.sleep(10);
synchronized (this)//这里的this指的是调用该方法的对象,也就是u
{//执行同步代码块时要检查该线程是否取得对象u的锁
this.cash += x;
System.out.println(Thread.currentThread().getName()+"运行结束,增加"+x+",当前账户余额:"+cash);
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public String toString()
{
return "User:" + code + ",cash="+cash;
}
}
三、效果展示
四、同步方法
public synchronized void 函数名(形参列表);
这种机制确保了同一时刻对于每一个对象,其所有声明为synchronized的成员方法中最多只有一个处于可以执行状态
五、代码实现
package org.Thread;
public class ThreadDemo03
{
public static void main(String[] args)
{
User u = new User("张三",100);
MyThread t1 = new MyThread("线程A",u,20);
MyThread t2 = new MyThread("线程B",u,-60);
MyThread t3 = new MyThread("线程C",u,-80);
MyThread t4 = new MyThread("线程D",u,-30);
MyThread t5 = new MyThread("线程E",u,32);
MyThread t6 = new MyThread("线程F",u,21);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class MyThread extends Thread
{
private User u;
private int y = 0;
MyThread(String name,User u,int y)
{
super(name);
this.u = u;
this.y = y;
}
public void run()
{
u.oper(y);
}
}
class User
{
private String code;
private int cash;
User(String code,int cash)
{
this.code = code;
this.cash = cash;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public synchronized void oper(int x)
{
try{
Thread.sleep(10);
this.cash += x;
System.out.println(Thread.currentThread().getName()+"运行结束,增加"+x+",当前账户余额:"+cash);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public String toString()
{
return "User:" + code + ",cash="+cash;
}
}
六、 效果展示