1.继承类的方式
(1)定义Test类并继承Thread
public class Test extends Thread {
int begin;
public Test(int begin){
this.begin=begin;
}
public void run(){
for(int i=begin;i<30;i+=2){
System.out.print(i+" ");;
}
}
}
(2)在Main类中调用
public class Main {
public static void main(String[] args) {
Test test=new Test(1);
Test test2=new Test(2);
test.start();
test2.start();
}
}
注意:由于该模式继承Tread类,可以直接调用父类Thread的方法,Java机制中只能单继承,
2.实现接口的方式
(1)创建Test类并实现Runnable接口
public class Test implements Runnable {
int begin;
public Test(int begin){
this.begin=begin;
}
public void run(){
for(int i=begin;i<30;i+=2){
System.out.print(i+" ");;
}
}
}
(2)创建Main类实例化Test类,并创建线程
public class Main {
public static void main(String[] args) {
Test test = new Test(1);
Test test2 = new Test(2);
// 设置线程1
Thread th1 = new Thread(test);
// 设置线程2
Thread th2 = new Thread(test2);
th1.start();
th2.start();
}
}
注意:该类实现接口Runnable,调用Statr()方法调用多线程