自学打卡 java之线程类

 

一、获取当前运行的线程

package practice;
//获取当前运行的线程
public class Chapter9 {
    public static void main(String args[]) {
        String name;
        int p;
        Thread curr;
        
        curr=Thread.currentThread();
        System.out.println(curr);
        
        p=curr.getPriority();
        name=curr.getName();
        System.out.println(p+ " "+name);
        
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

}

 

二、通过继承实现多线程

package practice;
//通过继承实现多线程
class UserThread extends Thread{       //定义多线程类
    int sleepTime=0;

    public UserThread(String id){     //构造函数
        super(id);
        sleepTime=(int)(Math.random()*1000);  //随机产生睡眠时间,睡眠0~1000毫秒
        System.out.println("线程名:"+getName()+",睡眠: "+sleepTime+"ms");
    }
    
    public void run() {       //覆盖父类方法
        try {
            Thread.sleep(sleepTime);     //可能产生中断异常
        }catch(InterruptedException e) {
            System.out.println("运行异常!"+e.toString());
        }
        System.out.println("当前运行的线程是:"+getName());
    }
}
public class Chapter9 {
    public static void main(String args[]) {
        UserThread t1,t2,t3,t4;       //定义4个线程引用
        t1=new UserThread("No 1");
        t2=new UserThread("No 2");
        t3=new UserThread("No 3");
        t4=new UserThread("No 4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

}

三、通过实现Runnable接口创建多线程

package practice;
//通过实现Runnable接口创建多线程
class UserThread  implements Runnable {       //实现接口,定义多线程类
    int num;  
    UserThread(int n){num=n;}           //构造函数          
    public void run() {                   //run方法的实现
        for(int i=0;i<3;++i) 
            System.out.println("运行线程:"+num);
        System.out.println("结束:"+num);
    }
}
public class Chapter9 {
    public static void main(String args[]) {
         Thread mt1=new Thread(new UserThread(1));
         Thread mt2=new Thread(new UserThread(2));
         mt1.start();
         mt2.start();
         try {
            mt1.join();          //等待线程死亡
            mt2.join();
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
         
    }

}
 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值