Java的多线程实现方法

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()方法调用多线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值