003 - 创建线程的方式

1 - 简单代码示例
  • 继承Thread类
public class PrimeThread extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-" + i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
// 测试类
public class testMain {

    public static void main(String[] args)  {
        PrimeThread t1 = new PrimeThread();
        PrimeThread t2 = new PrimeThread();
        t1.start();
        t2.start();
    }

  • 实现Runnable接口
public class PrimeRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-" + i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
// 测试类
public class testMain {

   public static void main(String[] args)  {
        Thread t1 = new Thread(new PrimeRunnable());
        Thread t2 = new Thread(new PrimeRunnable());
        t1.start();
        t2.start();
    }
  • 上边两种方式, 输出结果类似 (看出 每次执行结果都不确定)

    Thread-0-0
    Thread-1-0
    Thread-0-1
    Thread-1-1
    Thread-1-2
    Thread-0-2
    Thread-0-3
    Thread-1-3
    Thread-0-4
    Thread-1-4
    Thread-0-5
    Thread-1-5
    Thread-0-6
    Thread-1-6
    Thread-0-7
    Thread-1-7
    Thread-0-8
    Thread-1-8
    Thread-1-9
    Thread-0-9
    
2 - 异常处理
  • 出现了异常,线程中也不需向外抛,即使跑出来,主线程也不一定接收到
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值