62,614
社区成员
发帖
与我相关
我的任务
分享
public class test {
public static int data=0; // share data
public static boolean flag= false; // control run()
public static void main(String[] args) throws InterruptedException{
TestSync ts = new TestSync(false);
Thread t10= new Thread(ts);
Thread t11= new Thread(ts);
Thread t20 = new Thread(ts);
t10.start();
Thread.sleep(500); // 使得t10线程启动
t11.start();
Thread.sleep(500);// 使得t11线程启动
test.flag=true;
t20.start();
}
}
class TestSync implements Runnable{
boolean flag=false; // control test1
public TestSync(boolean flag) {
super();
this.flag = flag;
}
public synchronized void test1() throws InterruptedException{
if(this.flag==false)
{
test.data= 100;
Thread.sleep(2000);
System.out.println(test.data+" test1");
this.flag= true;
}
else
{
test.data= 200;
//Thread.sleep(2000);
System.out.println(test.data);
this.flag= false;
}
}
public synchronized void test2() throws InterruptedException{
test.data = 500;
System.out.println(test.data+" test2");
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
if(test.flag==false){
test1();
}else{
test2();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Main{
public static void main(String[] args) throws InterruptedException {
Fair fair = new Fair(true);//true 用使用公平策略 false 使用非公平策略
for(int i=1; i< 50; i++){
new FairTestThread(fair, (new Random().nextInt(2) + 1)).start();
}//for
}
}
public class Fair {
private final ReentrantLock lock;
public Fair(boolean fair){
lock = new ReentrantLock(fair);
}
//模拟一个较耗时的task
public void testFair1() throws InterruptedException{
lock.lock();
try{
for(int i=0; i<100000; i++){}
}finally{
lock.unlock();
}//finally
}
//模拟一个较快完成的task
public void testFair2() throws InterruptedException{
lock.lock();
try{
for(int i=0; i<1000; i++){}
}finally{
lock.unlock();
}//finally
}
}
public class FairTestThread extends Thread {
private Fair fair;
private int type = 1;
public FairTestThread(Fair fair, int type) {
this.fair = fair;
this.type = type;
}
public void run() {
long start;
try {
while (!Thread.currentThread().isInterrupted()) {
start = System.nanoTime();
if(type == 1)
fair.testFair1();
else
fair.testFair2();
System.out.println((System.nanoTime() - start));
}// while
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}//catch
}
}
if(this.flag==false)
{
test.data= 100;
Thread.sleep(2000);
System.out.println(test.data+" test1");
this.flag= true;
}
问题一:t10最先运行,500毫秒后t11开始运行并等待test1()的锁释放,注意是2000毫秒后test1()才释放,在t11等待的过程中t20开始运行并且也等待t10 释放test1()的锁。所以t11,t20就会进入等待队列ContentionList,但由于ContentionList是后进先出,所以t20先运行。public synchronized void test1()
的写法基本等于 synchronized(this),也就是调用test1()或test2()方法时等于给当前TestSync对象加了同步锁,所以每次都只有一个线程根据判断能调用到test1()或test2()