黑马程序员技术交流社区
标题:
同步部分锁的验证
[打印本页]
作者:
姬光普
时间:
2015-5-20 23:47
标题:
同步部分锁的验证
看了视频后,对同步安全锁的验证,这是老师视频上举得例子
1.同步代码块中的锁就是一个简单的对象,很具有随意性
代码:
class Test implements Runnable
{
private int tick = 100;
Object obj = new Object();
public void run()
{
while(tick > 0)
{
synchronized(obj)
{
if(tick > 0)
{
try
{
Thread.sleep(1);
}
catch(Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"...sale..."+tick--);
}
}
}
}
}
public class Test1
{
public static void main(String[] args)
{
Test t = new Test();
Thread d1 = new Thread(t);
Thread d2 = new Thread(t);
Thread d3 = new Thread(t);
Thread d4 = new Thread(t);
d1.start();
d2.start();
d3.start();
d4.start();
}
}
复制代码
2.同步函数中的锁是this,下面代码中
代码:
package org.heima1;
public class Test2 {
/**
* 验证同步函数的锁是不是this,利用同步代码块和同步函数两种方式同步进行。如果是this,则遵从了同步的前提:必须是多个线程使用同一个锁,不会输出0
*/
public static void main(String[] args) {
Tickets t=new Tickets();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try {
Thread.sleep(10);//停一下主线程
} catch (InterruptedException e) {
e.printStackTrace();
}
t.flag=false;
t2.start();
}
}
class Tickets implements Runnable{
private int num=1000;//总共1000张票
Object obj=new Object();
Boolean flag=true;
public void run(){
if(flag){
while(true){
//synchronized(obj){//如果用obj则两个线程不是共用一个锁,产生安全问题,直接导致输出0
synchronized(this){//如果用this锁,则没有输出0,表示两者用的是同一个锁
if(num>0){
try{
Thread.sleep(10);
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName()+"---代码块----第"+num--);
}
}
}
}
else {
while(true)
show();
}
}
public synchronized void show(){ //同步函数
if(num>0){
try{
Thread.sleep(10);
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName()+"----同步函数----第"+num--);
}
}
}
复制代码
3.静态同步函数使用的锁是该方法所在类的字节码对象,也就是类名.class
代码示例:
public class Test3 {
/**
* 验证静态同步函数的锁是不是所在类的字节码对象,利用同步代码块和同步函数两种方式同步进行。
*/
public static void main(String[] args) {
Tickets2 t=new Tickets2();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try {
Thread.sleep(10);//停一下主线程
} catch (InterruptedException e) {
e.printStackTrace();
}
t.flag=false;
t2.start();
}
}
class Tickets2 implements Runnable{
private static int num=100;//总共1000张票
Object obj=new Object();
Boolean flag=true;
public void run(){
if(flag){
while(true){
//synchronized(obj){//如果用obj则两个线程不是共用一个锁,产生安全问题,直接导致输出0
//synchronized(this){//如果用this则两个线程不是共用一个锁,产生安全问题,直接导致输出0
synchronized(Tickets2.class){//如果用Tickets2.class锁,则没有输出0,表示两者用的是同一个锁
if(num>0){
try{
Thread.sleep(10);
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName()+"---代码块----第"+num--);
}
}
}
}
else {
while(true)
show();
}
}
public static synchronized void show(){ //同步函数
if(num>0){
try{
Thread.sleep(10);
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName()+"----同步函数----第"+num--);
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2