线程的休眠,以及多线程练习

一种能够控制线程的行为方法是调用sleep()方法,这种方法需要一个参数用于指定该进程休眠短时间,这个时间是要以毫秒为单位

tyr{
Thread.sleep(2000);
}catch(Interruption e)
{
e.printStackTrace();
}

上面这段代码会让线程量秒内不会进入就绪状态。

package duoxiancheng;
import java.awt.*;
import javax.swing.*;
import java.util.Random;


public class SleepMethodTest extends JFrame {

	private Thread t;
private static Color[] color= {Color.BLACK,Color.BLUE,
		Color.CYAN,Color.GREEN,Color.ORANGE,Color.YELLOW,
		Color.RED,Color.PINK};
private static final Random rand=new Random();
private static Color getC() {
	return color[rand.nextInt(color.length)];
}

public SleepMethodTest()
{
t=new Thread(new Runnable() {
		int x=30;
		int y=50;
		public void run()
		{
			while(true)
			{
				try {
					Thread.sleep(100);
				}catch(InterruptedException e) {
					e.printStackTrace();
				}
				
				Graphics graphics=getGraphics();
				graphics.setColor(getC());
				graphics.drawLine(x, y, 100, y++);
				if(y>=80) {
					y=50;
				}
			}
		}
});
t.start();
}	







	public static void main(String[] args) {
	 	// TODOto-generated method stub
		
		SleepMethodTest.init(new SleepMethodTest(),100,100);
		}
	
	public static void init(JFrame frame,int width,int height)
	{
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(width, height);
		frame.setVisible(true);
		}

	} 

这段代码是产生一个窗体,窗体内莫一行自动划线,颜色随机

猜你喜欢

转载自blog.csdn.net/gaoweiyuan1996/article/details/81943778