Java开启新线程的两种方式(个人笔记)

1.继承Thread类

 class TestThread extends Thread
        {
          @Override
            public void run()
          {
              for(int i=1;i<=10;i++)
              System.out.println("线程"+Thread.currentThread().getName()+"运行第"+i+"次");
          }
        }


public class JustATest{
    public static void main(String[] args) {
       new TestThread().start();
 
 }
}

我们在TextThread类中重写了Thread类中的run方法,然后在main函数里通过start开始线程。

2.实现Runable接口

class  TestThread implements Runnable
{
    private int i=10;
    public void run()
    {
        for(;i>0;i--)
            System.out.println("线程"+Thread.currentThread().getName()+"运行第"+i+"次");
    }
}

public class JustATest{
    public static void main(String[] args) {
        TestThread a=new TestThread();
        new Thread(a,"1").start();
        new Thread(a,"2").start();
        new Thread(a,"3").start();
 }
}

在实现Runable接口后,我们将一个TestThread的实例传入一个Thread对象中,并通过start开启。

因为Thread保留了TestThread实例的引用,所以当任意一个线程调用run方法时都会对实例a的属性i进行操作,理论上三个线程应该一共执行十次,但因为多个线程共同执行,使得运行结果如下:

线程1运行第10次
线程3运行第10次
线程2运行第10次
线程3运行第8次
线程1运行第9次
线程3运行第6次
线程2运行第7次
线程3运行第4次
线程1运行第5次
线程3运行第2次
线程2运行第3次
线程1运行第1次

进程已结束,退出代码为 0

这时我们可以使用同步代码块保证线程的安全。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值