搬家后的博客链接: IT客栈 www.itkezhan.org
1.ReentrantLock(重入锁)可以加多层锁的意思。
用法
class X{
private final ReentrantLock lock = new ReentrantLock();
public void m()
{
lock.lock();
try{
//需要保证线程安全的代码编写区域
}
finally
{
lock.unlock(); //上面的代码执行完了之后对其进行解锁。以便其他线程可以访问。
}
}
}
2.synchronized(英文翻译:同步的)
同步代码块
synchronized(obj)
{
//这里是编写同步代码块。即需要保护的代码区域 “临界区”
}
同步方法
class test{
public synchronized void t()
{
//这个方法不能让多个线程同时访问。保证了某一个时刻只有一个线程执行它。
}
}
========================================================================================
//ReentrantLock
import java.util.concurrent.locks.ReentrantLock;
class a{
private final ReentrantLock l = new ReentrantLock();
public void t()
{
l.lock();
try
{
System.out.print("同一时间只有一个调用我\t");
System.out.println(Thread.currentThread().getName());
}
finally
{
l.unlock();
}
}
}
class myThread extends Thread{
a a1;
myThread(a a1)
{
this.a1 = a1;
}
@Override
public void run()
{
for(int i = 0 ; i< 10 ; i++)
{
a1.t();
try
{
myThread.sleep(1);
}
catch(InterruptedException e)
{
}
}
}
}
public class test{
public static void main(String[] args)
{
a a1 = new a();
myThread m1 = new myThread(a1);
myThread m2 = new myThread(a1);
m1.start();
m2.start();
}
}
class a{
//synchronized 同步代码块实例
public void t()
{
System.out.print("同一时间只有一个调用我\t");
System.out.println(Thread.currentThread().getName());
}
}
class myThread extends Thread{
a a1;
myThread(a a1)
{
this.a1 = a1;
}
public void run()
{
for(int i = 0 ; i< 10 ; i++)
{
synchronized(a1)
{
a1.t();
}
try
{
this.sleep(1);
}
catch(InterruptedException e)
{
}
}
}
}
public class test{
public static void main(String[] args)
{
a a1 = new a();
myThread m1 = new myThread(a1);
myThread m2 = new myThread(a1);
m1.start();
m2.start();
}
}
//synchronized 方法实例
class a{
public synchronized void t()
{
System.out.print("同一时间只有一个调用我\t");
System.out.println(Thread.currentThread().getName());
}
}
class myThread extends Thread{
a a1;
myThread(a a1)
{
this.a1 = a1;
}
public void run()
{
for(int i = 0 ; i< 10 ; i++)
{
a1.t();
try
{
this.sleep(1);
}
catch(InterruptedException e)
{
}
}
}
}
public class test{
public static void main(String[] args)
{
a a1 = new a();
myThread m1 = new myThread(a1);
myThread m2 = new myThread(a1);
m1.start();
m2.start();
}
}