更多库之谜总结 (一)

2014-11-24 02:43:04 · 作者: · 浏览: 3

1.在使用多线程时要注意run方法和start方法的区别
t.run();main线程调用t的run方法,并没有创建新线程。

t.start();创建一个新的线程t,并执行。

view plaincopy to clipboardprint public class PuzzleDemo76{
public static synchronized void main(String args[]){ //主线程获得PuzzleDemo76对象的锁
Thread t = new Thread(){
public void run(){
pong();
}
};
t.start();
System.out.println("ping");
}
static synchronized void pong(){ //等待main线程执行完毕,才能够使得t线程获得锁
System.out.println("pong");
}
}
public class PuzzleDemo76{
public static synchronized void main(String args[]){ //主线程获得PuzzleDemo76对象的锁
Thread t = new Thread(){
public void run(){
pong();
}
};
t.start();
System.out.println("ping");
}
static synchronized void pong(){ //等待main线程执行完毕,才能够使得t线程获得锁
System.out.println("pong");
}
}

2.Thread的join()方法注意点
表示正在被链接的Thread实例调用wait方法,因此会释放锁。

因此如果你需要某个对象的锁的完全控制,则必须确保没有其他线程访问。

view plaincopy to clipboardprint import java.util.*;
public class PuzzleDemo77{
public static void main(String args[])throws Exception{
final Worker w = new Worker();
Thread t = new Thread(w);
t.start();
Timer timer = new Timer(true);
timer.schedule(new TimerTask(){
public void run(){
w.keepWorking();
}
},500);
Thread.sleep(400);
w.quit(); //获得w的锁,并执行方法
}
}
class Worker implements Runnable{
private volatile boolean quitTime = false;
public void run(){
while(!quitTime){
pretendToWork();
}
System.out.println("Beer is good");
}
private void pretendToWork(){
try{
Thread.sleep(300);
}
catch(Exception e){

}
}
synchronized void quit() throws Exception{
quitTime = true;
Thread.yield();//释放锁
}
synchronized void keepWorking(){
quitTime = true;
}
}
import java.util.*;
public class PuzzleDemo77{
public static void main(String args[])throws Exception{
final Worker w = new Worker();
Thread t = new Thread(w);
t.start();
Timer timer = new Timer(true);
timer.schedule(new TimerTask(){
public void run(){
w.keepWorking();
}
},500);
Thread.sleep(400);
w.quit(); //获得w的锁,并执行方法
}
}
class Worker implements Runnable{
private volatile boolean quitTime = false;
public void run(){
while(!quitTime){
pretendToWork();
}
System.out.println("Beer is good");
}
private void pretendToWork(){
try{
Thread.sleep(300);
}
catch(Exception e){

}
}
synchronized void quit() throws Exception{
quitTime = true;
Thread.yield();//释放锁
}
synchronized void keepWorking(){
quitTime = true;
}
}

3.HashSet的问题
HashSets = new HashSet();

Iterator i = s.iterator(); 这里的i是HashMap.keyIterator类型的。但是因为这个类型是不同包中且非公共的,因此不能调用他的方法。

class HashSet{

private transient HashMap map;

public Iterator iterator() {
return map.keySet().iterator();
}

}

view plaincopy to clipboardprint import java.util.*;
import java.lang.reflect.*;
public class PuzzleDemo78{
public static void main(String args[])throws Exception{
Set s = new HashSet();
s.add("foo");
Iterator iter = s.iterator();
Method m = Iterator.class.