栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425223.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号