Posts Tagged ‘Thread’

How do you create a Thread

Threads:
Thread is a line of execution.In a single-threaded system there is only one execution line (i.e) only one part of program is in the process of execution at any one time

To create a new thread:

Thread mythread = new thread(this);

this referes the current applet & mythread is a variable

Example:

import java.awt.*;
import java.applet.Applet;
public class MovingBall extends Applet implements runnable
{
Thread mythread=null;
int position=0;
public void start()
{
mythread=new Thread(this);
mythread.start();
}
public void run()
{
while(true)
{
for(position=0;position) {
repaint();
try
{mythread.sleep(100);
}
catch(InterruptedException e)
{
}
}
}
}
public void stop()
{
mythread.stop();
mythread = null;
}
public void paint(Graphics g)
{
g.setColor(Color.gray);
g.fillOval(position,50,30,30);
g.setColor(Color.black);
g.fillOval(position+6,58,5,5);
g.fillOval(position+20,58,5,5);
g.drawLine(position+15,58, position+15,68);
g.drawLine(position+12,68, position+15,68);
g.drawLine(position,45,30,30,-50,-70);
}
}

Popularity: 7% [?]

Designed by: Business Web Hosting | Thanks to Buy Icons, travel tips and Used Cars