1、创建一个同步机制。如实现4个线程,其中两个线程加1,两个线程对变量减1.
2、写一个与实现hashMap相似的类。
(1)类长度是定值,超出长度,抛出异常或等待删除一个后再插入。
(2)写一个具有延迟添加的方法put(Key k,Value v,long time),超过时间后失效。
(3)如果一个类近期被get()过,那么延长失效时间。
------解决方案--------------------
1.
- Java code
public class MyThread extends Thread{ public static int num = 0; public void run(){ add(); //根据题目意思不同线程 调用 add 或 del } public synchronized void math(int type){ switch(type){ case 1: ++num; break; case 2: --num; break; } } public void add(){ math(1); } public void del(){ math(2); }}
------解决方案--------------------
public class Test {
static int j = 0;
public static void main(String[] args){
MyThread1 mt1 = new MyThread1();
mt1.start();
MyThread1 mt2 = new MyThread1();
mt2.start();
MyThread2 mt3 = new MyThread2();
mt3.start();
MyThread2 mt4 = new MyThread2();
mt4.start();
}
static class MyThread1 extends Thread{
public void run(){
while(true){
try{
j = ++j;
this.sleep(1000);
System.out.println("此时j的值是"+j);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
static class MyThread2 extends Thread{
public void run(){
while(true){
try{
j = --j;
this.sleep(1000);
System.out.println("此时j的值是"+j);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
------解决方案--------------------
第二题 第三问不明白...
- Java code
import java.util.HashMap;public class H extends HashMap { private final int size = 2; public Object put(Object key, Object value, long nas) { if (this.size() > size) {//设置最大长度 throw new IllegalStateException(); } synchronized (this) { try { this.wait(nas);//设置延迟插入 } catch (Exception e) { e.printStackTrace(); } return super.put(key, value); } }}class Test { public static void main(String[] args) { H m = new H(); m.put("s", "ss", 1000L); m.put("d", "ss", 1000L); m.put("F", "ss", 1000L); m.put("f", "ss", 1000L); System.out.println(m.get("s")); }}
------解决方案--------------------
- Java code
public class TestThread { private int j; public TestThread(int j) {this.j = j;} private synchronized void inc(){ j++; System.out.println(j + "--Inc--" + Thread.currentThread().getName()); } private synchronized void dec(){ j--; System.out.println(j + "--Dec--" + Thread.currentThread().getName()); } public void run() { (new Dec()).start(); new Thread(new Inc()).start(); (new Dec()).start(); new Thread(new Inc()).start(); } class Dec extends Thread { public void run() { for(int i=0; i<100; i++){ dec(); } } } class Inc implements Runnable { public void run() { for(int i=0; i<100; i++){ inc(); } } } public static void main(String[] args) { (new TestThread(5)).run(); }}