同一个方法 ,两个线程任务,用不同的对象的锁,当其第一个线程释放锁1,第二个线程 才能进入?
public class RunTest implements Runnable{
String tname;
static int num = 0;
Object res;
public RunTest(String tname,Object res) {
// TODO Auto-generated constructor stub
this.tname = tname;
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (res) {
while(num<10){
num ++;
System.out.println(tname+"->"+num);
if(num==3){
try {
res.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
Object res1 = new Object();
Object res2 = new Object();
RunTest t1 = new RunTest("任务1",res1);
RunTest t2 = new RunTest("任务2",res2);
new Thread(t1).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(t2).start();
}
输出结果
任务1->1
任务1->2
任务1->3
任务2->4
任务2->5
任务2->6
任务2->7
任务2->8
任务2->9
任务2->10