`

线程面试

 
阅读更多

1. 子线程循环10次后,主线程循环100次,接着子线程循环10次后,主线程又循环100次,如此循环50次

package com.thread.ticket;
 
/**
 * 子线程循环10次后,主线程循环100次,接着子线程循环10次后,主线程又循环100次
 *  如此循环50次
 */
public class ThreadChange {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable(){
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 boShouldSub = true;
public synchronized void sub(int j){
if(!boShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println("sub:loop "+j+" data:"+ i);
}
boShouldSub = false;
this.notify();
 
}
 
public synchronized void main(int j){
if(boShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 100; i++) {
System.out.println("main:loop "+j+" data:"+ i);
}
 
boShouldSub = true;
this.notify();
 
}
}

 

 

package com.thread.ticket;
 
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
 
/**
 * 子线程循环10次后,主线程循环100次,接着子线程循环10次后,主线程又循环100次
 *  如此循环50次
 */
public class ThreadChangeBlock {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 50; i++) {
business.sub(i);
}
}
}).start();
 
for (int i = 0; i < 50; i++) {
business.main(i);
}
}
 
static class Business{
BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
 
{ 
try {
queue2.put(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 
 
 
public  void sub(int j){
try {
queue1.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 10; i++) {
System.out.println("sub:loop "+j+" data:"+ i);
}
try {
queue2.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
}
 
public  void main(int j){
try {
queue2.put(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 1; i <= 100; i++) {
System.out.println("main:loop "+j+" data:"+ i);
}
 
try {
queue1.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
}
}
 
 
package com.thread.ticket;
 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
/**
 * 子线程循环10次后,主线程循环100次,接着子线程循环10次后,主线程又循环100次
 *  如此循环50次
 */
public class ThreadChangeCondition {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 50; i++) {
business.sub(i);
}
}
}).start();
 
for (int i = 0; i < 50; i++) {
business.main(i);
}
}
 
static class Business{
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
private boolean boShouldSub = true;
public  void sub(int j){
lock.lock();
try{
if(!boShouldSub){
try {
//this.wait();
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println("sub:loop "+j+" data:"+ i);
}
boShouldSub = false;
//this.notify();
condition.signal();
 
}finally{
lock.unlock();
}
 
 
 
}
 
public  void main(int j){
lock.lock();
try{
if(boShouldSub){
try {
//this.wait();
condition.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 100; i++) {
System.out.println("main:loop "+j+" data:"+ i);
}
 
boShouldSub = true;
//this.notify();
condition.signal();
}finally{
lock.unlock();
}
 
}
}
 
}
 
package com.thread.ticket;
 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
/**
 * 子线程循环10次后,主线程循环100次,接着子线程1循环50次后,接着子线程2循环10次后,主线程又循环100次,接着子线程1循环50次后,接着子线程2循环10次
 *  如此循环50次
 */
public class ThreadChangeThreeCondition {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 50; i++) {
business.sub2(i);
}
}
}).start();
new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 50; i++) {
business.sub3(i);
}
}
}).start();
 
for (int i = 0; i < 50; i++) {
business.main(i);
}
}
 
static class Business{
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int shouldSub = 1;
public  void sub2(int j){
lock.lock();
try{
if(shouldSub != 2){
try {
condition2.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 50; i++) {
System.out.println("sub2:loop "+j+" data:"+ i);
}
shouldSub = 3;
condition3.signal();
 
}finally{
lock.unlock();
}
}
 
public  void sub3(int j){
lock.lock();
try{
if(shouldSub != 3){
try {
condition3.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println("sub3:loop "+j+" data:"+ i);
}
shouldSub = 1;
condition1.signal();
 
}finally{
lock.unlock();
}
}
 
public  void main(int j){
lock.lock();
try{
if(shouldSub != 1){
try {
//this.wait();
condition1.await();
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 100; i++) {
System.out.println("main:loop "+j+" data:"+ i);
}
 
shouldSub = 2;
//this.notify();
condition2.signal();
}finally{
lock.unlock();
}
 
}
}
 
}

 

 

2.设计4个线程,其中两个线程对j进行+1,另两个线程对j进行-1

 

package com.thread.ticket;
 
/**
 * 设计4个线程,其中两个线程对j进行+1,另两个线程对j进行-1.
 *
 */
public class ThreadIncDec {
private int j;
public static void main(String[] args) {
ThreadIncDec tid = new ThreadIncDec();
Inc inc = tid.new Inc();
Dec dec = tid.new Dec();
for (int i = 0; i < 2; i++) {
new Thread(inc).start();
new Thread(dec).start();
}
}
 
private synchronized void increment() {
System.out.println(Thread.currentThread().getName()+" Inc:"+j++);
}
 
private synchronized void decrement() {
System.out.println(Thread.currentThread().getName()+" Dec:"+j--);
}
 
class Inc implements Runnable{
public void run() {
for (int i = 0; i < 100; i++) {
increment();
}
}
}
 
class Dec implements Runnable{
public void run() {
for (int i = 0; i < 100; i++) {
decrement();
}
}
}
 
}

 

 

3.现有程序同时启动了4个线程去调用TestDo.doSome(key, value)方法,由于TestDo.doSome(key, value)方法内的代码是先暂停1秒,然后再输出以秒为单位的当前时间值,所以,会打印出4个相同的时间值,如下所示:

4:4:1258199615

1:1:1258199615

3:3:1258199615

1:2:1258199615

        请修改代码,如果有几个线程调用TestDo.doSome(key, value)方法时,传递进去的key相等(equals比较为true),则这几个线程应互斥排队输出结果,即当有两个线程的key都是"1"时,它们中的一个要比另外其他线程晚1秒输出结果,如下所示:

4:4:1258199615

1:1:1258199615

3:3:1258199615

1:2:1258199616

 总之,当每个线程中指定的key相等时,这些相等key的线程应每隔一秒依次输出时间值(要用互斥),如果key不同,则并行执行(相互之间不互斥)

 

package syn;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
 
/**现有程序同时启动了4个线程去调用TestDo.doSome(key, value)方法,由于TestDo.doSome(key, value)方法内的代码是先暂停1秒,然后再输出以秒为单位的当前时间值,所以,会打印出4个相同的时间值,如下所示:
4:4:1258199615
1:1:1258199615
3:3:1258199615
1:2:1258199615
        请修改代码,如果有几个线程调用TestDo.doSome(key, value)方法时,传递进去的key相等(equals比较为true),则这几个线程应互斥排队输出结果,即当有两个线程的key都是"1"时,它们中的一个要比另外其他线程晚1秒输出结果,如下所示:
4:4:1258199615
1:1:1258199615
3:3:1258199615
1:2:1258199616
 总之,当每个线程中指定的key相等时,这些相等key的线程应每隔一秒依次输出时间值(要用互斥),如果key不同,则并行执行(相互之间不互斥)**/
//不能改动此Test类
public class Test extends Thread{
 
private TestDo testDo;
private String key;
private String value;
 
public Test(String key,String key2,String value){
this.testDo = TestDo.getInstance();
/*常量"1"和"1"是同一个对象,下面这行代码就是要用"1"+""的方式产生新的对象,
以实现内容没有改变,仍然相等(都还为"1"),但对象却不再是同一个的效果*/
this.key = key+key2; 
this.value = value;
}
 
 
public static void main(String[] args) throws InterruptedException{
Test a = new Test("1","","1");
Test b = new Test("1","","2");
Test c = new Test("3","","3");
Test d = new Test("4","","4");
System.out.println("begin:"+(System.currentTimeMillis()/1000));
a.start();
b.start();
c.start();
d.start();
 
}
 
public void run(){
testDo.doSome(key, value);
}
}
 
class TestDo {
 
private TestDo() {}
private static TestDo _instance = new TestDo();
public static TestDo getInstance() {
return _instance;
}
 
private CopyOnWriteArrayList keys = new CopyOnWriteArrayList();
//private ArrayList keys = new ArrayList();iterator的时候不能对数据进行修改
public void doSome(Object key, String value) {
     Object o = key;
     if(!keys.contains(o)){
     keys.add(o);
     }else{
     for(Iterator iter =keys.iterator();iter.hasNext();){
     Object oo = iter.next();
     if(oo.equals(o)){
     o = oo;
     break;
     }
     }
     }
 
synchronized (o) 
// 以大括号内的是需要局部同步的代码,不能改动!
{
try {
Thread.sleep(1000);
System.out.println(key+":"+value + ":"
+ (System.currentTimeMillis() / 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
 
}
 

 

 

4.现有的程序代码模拟产生了16个日志对象,并且需要运行16秒才能打印完这些日志,

请在程序中增加4个线程去调用parseLog()方法来分头打印这16个日志对象,程序只需要运行4秒即可打印完这些日志对象

package read;
 
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
//现有的程序代码模拟产生了16个日志对象,并且需要运行16秒才能打印完这些日志,
//请在程序中增加4个线程去调用parseLog()方法来分头打印这16个日志对象,程序只需要运行4秒即可打印完这些日志对象
public class Test {
 
public static void main(String[] args){
//final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(4);
for (int i = 0; i < 4; i++) {
new Thread(new Runnable(){
public void run() {
while(true)
try {
String log = queue.take();
parseLog(log);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
System.out.println("begin:"+(System.currentTimeMillis()/1000));
/*模拟处理16行日志,下面的代码产生了16个日志对象,当前代码需要运行16秒才能打印完这些日志。
修改程序代码,开四个线程让这16个对象在4秒钟打完。
*/
for(int i=0;i<16;i++){  //这行代码不能改动
final String log = ""+(i+1);//这行代码不能改动
{
//Test.parseLog(log);
try {
queue.put(log);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
}
}
}
 
//parseLog方法内部的代码不能改动
public static void parseLog(String log){
System.out.println(log+":"+(System.currentTimeMillis()/1000));
 
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
 
}
 

 

5.现成程序中的Test类中的代码在不断地产生数据,然后交给TestDo.doSome()方法去处理,就好像生产者在不断地产生数据,消费者在不断消费数据。

请将程序改造成有10个线程来消费生成者产生的数据,这些消费者都调用TestDo.doSome()方法去进行处理,

故每个消费者都需要一秒才能处理完,程序应保证这些消费者线程依次有序地消费数据,只有上一个消费者消费完后,

下一个消费者才能消费数据,下一个消费者是谁都可以,但要保证这些消费者线程拿到的数据是有顺序的

 

 
package queue;
 
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
//现成程序中的Test类中的代码在不断地产生数据,然后交给TestDo.doSome()方法去处理,就好像生产者在不断地产生数据,消费者在不断消费数据。
//请将程序改造成有10个线程来消费生成者产生的数据,这些消费者都调用TestDo.doSome()方法去进行处理,
//故每个消费者都需要一秒才能处理完,程序应保证这些消费者线程依次有序地消费数据,只有上一个消费者消费完后,
//下一个消费者才能消费数据,下一个消费者是谁都可以,但要保证这些消费者线程拿到的数据是有顺序的
public class Test {
 
public static void main(String[] args) {
        final SynchronousQueue<String> queue = new SynchronousQueue<String>();
        final Lock lock = new ReentrantLock();
        final Semaphore sp = new  Semaphore(1);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
//lock.lock();
sp.acquire();
String input = queue.take();
String output = TestDo.doSome(input);
System.out.println(Thread.currentThread().getName()+ ":" + output);
sp.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//lock.unlock();
}
}
}).start();
}
System.out.println("begin:"+(System.currentTimeMillis()/1000));
for(int i=0;i<10;i++){  //这行不能改动
String input = i+"";  //这行不能改动
try {
queue.put(input);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
}
}
}
 
//不能改动此TestDo类
class TestDo {
public static String doSome(String input){
 
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String output = input + ":"+ (System.currentTimeMillis() / 1000);
return output;
}
}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics