java关于多线程的面试题(三道)

第一题题目


原代码

第二题题目


第二题题目原题目的运行效果


想要实现的效果


第三题题目


第一题的原代码

public class Test {
	
	public static void main(String[] args){
  
	System.out.println("begin:"+(System.currentTimeMillis()/1000));
		
		for(int i=0;i<16;i++){  //这行代码不能改动
			final String log = ""+(i+1);//这行代码不能改动
			{
					
	     			Test.parseLog(log);
			}
		}
	}
	
	//parseLog方法内部的代码不能改动
	public static void parseLog(String log){
		System.out.println(log+":"+(System.currentTimeMillis()/1000));
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
	
}
第二题题目原代码
public class Test {

	public static void main(String[] args) {
		System.out.println("begin:"+(System.currentTimeMillis()/1000));
		for(int i=0;i<10;i++){  //这行不能改动
			String input = i+"";  //这行不能改动
			String output=TestDo.doSome(input);
			System.out.println(Thread.currentThread.getName()+":"+output);

}
	}
}

//不能改动此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;
	}
}
第三题题目原代码
//不能改动此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; 
/*		a = "1"+"";
		b = "1"+""
*/
		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;
	}

	public void doSome(Object key, String value) {
		// 以大括号内的是需要局部同步的代码,不能改动!
		{
			try {
				Thread.sleep(1000);
				System.out.println(key+":"+value + ":"
						+ (System.currentTimeMillis() / 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

题目是空中网以往的面试题 来自已故技术前辈张孝祥老师的相关学习资料

下一篇会给出参考答案

猜你喜欢

转载自blog.csdn.net/u014353343/article/details/74538166