㈠ java Thread BLOCKED和WAITING两种状态的区别
BLOCKED状态
线程处于BLOCKED状态的场景。
当前线程在等待一个monitor lock,比如等待执行synchronized代码块或者使用synchronized标记的方法。
在synchronized块中循环调用Object类型的wait方法,如下是样例
synchronized(this)
{
while (flag)
{
obj.wait();
}
// some other code
}
WAITING状态
线程处于WAITING状态的场景。
调用Object对象的wait方法,但没有指定超时值。
调用Thread对象的join方法,但没有指定超时值。
调用LockSupport对象的park方法。
提到WAITING状态,顺便提一下TIMED_WAITING状态的场景。
TIMED_WAITING状态
线程处于TIMED_WAITING状态的场景。
调用Thread.sleep方法。
调用Object对象的wait方法,指定超时值。
调用Thread对象的join方法,指定超时值。
调用LockSupport对象的parkNanos方法。
调用LockSupport对象的parkUntil方法。
㈡ 关于java中的interrupt()方法疑问
当一个线程处于不可运行状态时,如键盘输入,调用Thread.join()方法或者Thread.sleep()方法,从而线程被阻塞了。调用interrupt()可以使一个被阻塞的线程抛出一个中断异常,从而使线程提前结束阻塞状态,退出堵塞代码。
你可参照下http://daydayup1989.javaeye.com/blog/785581
㈢ 一个画直线的JAVA小程序
//你的类我改了错误,现在可以用了 
//有错的地方我标了“//有错” 
//请认真看,我花了时间改的 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
public class DrawLine { 
public static void main(String[] args) { 
new MyFrame(200, 200, 300, 300); 
} 
} 
class MyFrame extends Frame { 
Point p = new Point(); 
Point q = new Point(); 
boolean flag; 
ArrayList<Point> a1 = new ArrayList<Point>(); 
ArrayList<Point> a2 = new ArrayList<Point>(); 
MyFrame(int x, int y, int w, int h) { 
super("drawline"); 
setBounds(x, y, w, h); 
setBackground(Color.white); 
Button b = new Button("Line"); 
add(b, BorderLayout.NORTH); 
b.addActionListener(new ButtonMonitor()); 
addMouseListener(new MouseMonitor()); 
addWindowListener(new WindowMonitor()); 
setVisible(true); 
} 
class ButtonMonitor implements ActionListener { 
public void actionPerformed(ActionEvent e) { 
if (e.getActionCommand() == "Line") { 
flag = true; 
} 
repaint(); 
} 
} 
public void paint(Graphics g) { 
Iterator<Point> i1 = a1.iterator(); 
Iterator<Point> i2 = a2.iterator(); 
while (i1.hasNext() && i2.hasNext()) { 
p = i1.next(); 
q = i2.next();//有错 
Color c = g.getColor(); 
g.setColor(Color.red); 
g.drawLine(p.x, p.y, q.x, q.y); 
g.setColor(c); 
} 
} 
public void addPoint1(Point p) { 
a1.add(p); 
} 
public void addPoint2(Point p) { 
a2.add(p); 
} 
class MouseMonitor extends MouseAdapter { 
public void mousePressed(MouseEvent e) { 
MyFrame my = (MyFrame) e.getSource(); 
addPoint1(new Point(e.getX(), e.getY()));//有错 my->e 
repaint(); 
} 
public void mouseReleased(MouseEvent e) {//有错mouseDragged->mouseReleased 
MyFrame my = (MyFrame) e.getSource(); 
addPoint2(new Point(e.getX(), e.getY()));//有错 
repaint(); 
} 
} 
class WindowMonitor extends WindowAdapter { 
@Override 
public void windowClosing(WindowEvent e) { 
setVisible(false); 
System.exit(0); 
} 
} 
}