1. What is a thread?
Thread: It is the smallest unit that the operating system can perform operation scheduling. It is included in the process and is the actual operating unit in the process. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.
2. Under what circumstances will threads be used?
Multi-threading is needed when multiple tasks are needed at the same time. For a simple example, when we are executing a thread, the thread may draw a long straight line, it takes a certain amount of time to complete, but the actual situation requires me to draw the first line when the second Article, Article 3. . . Start painting too. This is to use multi-threading. In one sentence: Run multiple tasks at the same time.
(Single-threaded example: after the first line is drawn, the second line will start)
3. How to create threads?
- Create a multi-threaded class (my name: DrawThread.java)
and define the parameters that need to be used
public DrawThread(int x,int y,Graphics g) {
this.x=x;
this.y=y;
this.g=g;
}
2. Pass the class object of DrawThread created in the main interface
DrawThread dThread=new DrawThread(x,y,g);//创建多线程类的的对象
dThread.start();//一定要用这个对象去启动线程!!
3. Rewrite the run function in DrawThread
public void run(){
Color pink=new Color(255,192,203);
g.setColor(pink);
for (int i = 0; i < 600; i++) {
g.fillOval(x+i, y, 80, 80);
try {
//睡眠10ms,用来减慢画的速度
Thread.sleep(10);//这一句是加进去得
} catch (Exception e2) {
// TODO: handle exception
}
}