日期:2014-05-19 浏览次数:20685 次
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();
}
}
}
}
------解决方案--------------------
第二题 第三问不明白...
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")); } }
------解决方案--------------------
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();