创建线程的两种方法继承Thread或者实现Runnable

方法一:
(1)定义一个类Mythead类继承自Thread
(2)在Mythread类里面重写Thread的run方法
(3)在测试类里面创建Mythrea类的对象
(4)使用Mythread的对象调用start方法开启线程

代码展示
Mythread类

public class Mythread extends Thread{


public Mythread() {
}

//有了带参构造以后系统的默认无参构造就没有了我们要手动给出
public Mythread(String name) {
super(name); //我把这个name 传递给父类
}

@Override
public void run() {
for (int i = 0 ; i<200 ;i++ ){

String thname = getName();
System.out.println(thname+":"+i);
}
}
}

测试类


public static void main(String[] args) {

//创建线程对象
Mythread mythread1 = new Mythread();
Mythread mythread2 = new Mythread();
Mythread mythread3 = new Mythread();

//给线程起个名
mythread1.setName("one");
mythread2.setName("two");
mythread3.setName("three");

//获取一下线程的优先级
// System.out.println(mythread1.getPriority());
// System.out.println(mythread2.getPriority());
// System.out.println(mythread3.getPriority());
/*]
如果我们没有给线程指定优先级的话 默认的优先级是 5
*/


//获取一下优先级的范围
// System.out.println("优先级的范围");
// System.out.println("最大优先级:"+Thread.MAX_PRIORITY); //10
// System.out.println("最小优先级:"+Thread.MIN_PRIORITY); //1
// System.out.println("默认优先级:"+Thread.NORM_PRIORITY); //5

//为我们的线程设置优先级
mythread1.setPriority(4);
mythread2.setPriority(5);
mythread3.setPriority(7);

//开线程
mythread1.start();
mythread2.start();
mythread3.start();



}

方法二:
(1)定义一个类MyRunnable类实现Runnable接口
(2)在MyRunnable类里面重写Runnable的run方法
(3)在测试类里面创建MyRunnable类的对象
(4)在测试类里面创建Thread类的对象,参数是MyRunnable类的对象,并且Thread类的构造方法可以设置线程的名字
(5)使用Thread的对象调用start方法开启线程

MyRunnable类

public class MyRunnable implements Runnable{
@Override
public void run() {

for (int i = 0 ; i< 100; i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}


}
}

测试类


public static void main(String[] args) {

// 创建myRunnable对象
MyRunnable myRunnable = new MyRunnable();

//创建线程对象 参数是myRunnable
Thread thread1 = new Thread(myRunnable,"线程1"); //第二个参数是给线程设置名字
Thread thread2 = new Thread(myRunnable,"线程2");

//开启线程
thread1.start();
thread2.start();



}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值