您的位置:首页 > 职场人生

面试题,子线程10次子线程2执行20次与主线程100次来回循环执行50次

2014-08-10 22:42 260 查看
//	面试题,子线程2执行10次子线程2执行20次 与主线程100次来回循环执行50次
public class interview {

public static void main(String[] args) {
final Business b = new Business();
new Thread(new Runnable(){
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
b.sub2(i);
}
}

}).start();

new Thread(new Runnable(){
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
b.sub3(i);
}
}

}).start();

for (int i = 1; i <= 50; i++) {
b.main(i);
}
}
}
class Business{
private int order=1;
Lock lock = new ReentrantLock();
Condition con1 = lock.newCondition();
Condition con2 = lock.newCondition();
Condition con3 = lock.newCondition();
public void sub2(int i){
lock.lock();
try {
while (order != 2) {
try {
con2.await();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub2 Thread is sequence of " + j
+ "..lamp of " + i);
}
System.out.println("/..................");
order = 3;
con3.signal();
} finally{
lock.unlock();
}
}
public void sub3(int i){
lock.lock();
try {
while (order != 3) {
try {
con3.await();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
for (int j = 1; j <= 20; j++) {
System.out.println("sub3 Thread is sequence of " + j
+ "..lamp of " + i);
}
System.out.println("/..................");
order = 1;
con1.signal();
} finally{
lock.unlock();
}
}
public void main(int i){
lock.lock();
try {
while (order != 1) {
try {
con1.await();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("main Thread is sequence of " + j
+ "..lamp of " + i);
}
order = 2;
System.out.println("........................");
con2.signal();
} finally {
lock.unlock();
}
}
}


本文出自 “要么拼命,要么滚回去!” 博客,请务必保留此出处http://jiangzuun2014.blog.51cto.com/8732469/1538354
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐