1.继承Thread类,重写run()函数
Thread中的方法
package run;
public class Threadsimple extends Thread {
public Threadsimple(String name) {
setName(name);
}
public void run() {
int i=0;
for(;i<10;i++) {
try {
System.out.println(i+" "+this.getName());
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Threadsimple thread=new Threadsimple("ieng");
Threadsimple thread1=new Threadsimple("sing");
thread.start(); //线程开始工作
thread1.start(); //线程开始工作
}
}
Thread中还有sleep()函数,该函数用来休眠的,单位是ms,即毫秒
2、继承Runnable接口,重写run()方法
使用也跟Thread相似
只要改掉声明时的参数就行了
package Runnable1;
public class Runnable implements java.lang.Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
int i=0;
for(;i<10;i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
Thread thread=new Thread(new Runnable());
thread.start();
}
}