最近找工作,看了一些面试题,面试中经常遇到线程的问题,所以特意看了一些线程方面的题,这也是真正接触到线程的知识,这儿有一个很好的线程面试题,分享一下:
题目:
子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。
package com.zdsoft.demo;
public class TraditionalThreadCommunication {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 50; i++) {
business.sub(i);
}
}
}).start();
for(int i = 0; i < 50; i++) {
business.main(i);
}
}
}
class Business {
private boolean bShowSub = true;
public synchronized void sub(int i) {
while(!bShowSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j = 0; j < 10; j++) {
System.out.println("sub thread sequece of "+ j + ", loop of " + i);
}
bShowSub = false;
this.notify();
}
public synchronized void main(int i) {
while(bShowSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j = 0; j < 20; j++) {
System.out.println("main thread sequece of "+ j + ", loop of " + i);
}
bShowSub = true;
this.notify();
}
}
下面的例子比上面的难度稍微大了一点,是子线程1循环2次,接着子线程2运行两次,然后子线程3循环2次,然后又子线程1循环2次,以此类推,一共循环50十次,
package com.zdsoft.demo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TraditionalThreadCondition {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 50; i++) {
business.sub1(i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 50; i++) {
business.sub2(i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 50; i++) {
business.sub3(i);
}
}
}).start();
}
static class Business {
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int showSub = 1;
public void sub1(int i) {
lock.lock();
try{
while(showSub != 1) {
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j = 0; j < 2; j++) {
System.out.println("sub1 thread sequece of "+ j + ", loop of " + i);
}
showSub = 2;
condition2.signal();
}finally {
lock.unlock();
}
}
public void sub2(int i) {
lock.lock();
try{
while(showSub != 2) {
try {
condition2.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for(int j = 0; j < 2; j++) {
System.out.println("sub2 thread sequece of "+ j + ", loop of " + i);
}
showSub = 3;
condition3.signal();
}finally{
lock.unlock();
}
}
public void sub3(int i) {
lock.lock();
try{
while(showSub != 3) {
try {
condition3.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for(int j = 0; j < 2; j++) {
System.out.println("sub3 thread sequece of "+ j + ", loop of " + i);
}
showSub = 1;
condition1.signal();
}finally{
lock.unlock();
}
}
}
}