创建线程的两种方式:继承Thread类和实现Runnable接口

第一种方式:继承Thread类

步骤:1、定义类继承Thread

        2、覆写Thread类的run方法。 自定义代码放在run方法中,让线程运行

        3、调用线程的star方法,

该线程有两个作用:启动线程,调用run方法。

代码示例:

class Test extends Thread
{
    //private String name;
    Test(String name)
    {
        //this.name = name;
        super(name);
    }
    public void run()
    {
        for(int x=0; x<60; x++)
        {
            System.out.println((Thread.currentThread()==this)+"..."+this.getName()+" run..."+x);     //Thread.currentThread():获取当前线程对象
        }
    }

}


class ThreadTest 
{
    public static void main(String[] args) 
    {
        Test t1 = new Test("one---");
        Test t2 = new Test("two+++");
        t1.start();
        t2.start();
//        t1.run();
//        t2.run();

        for(int x=0; x<60; x++)
        {
            System.out.println("main....."+x);
        }
    }
}

第二种方式:实现Runnable接口

步骤:1、定义类实现Runnable接口

        2、覆盖Runnable接口中的run方法,运行的代码放入run方法中。

        3、通过Thread类建立线程对象。

        4、将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。

             因为,自定义的run方法所属的对象是Runnable接口的子类对象。所以要让线程去指定指定对象的run方法。就必须明确该run方法所属对象

       5、调用Thread类的start方法开启线程并调用Runnable接口子类的run方法

代码示例:卖票程序,多个窗口同时卖票

class Ticket implements Runnable
{
    private  int tick = 100;
    public void run()
    {
        while(true)
        {
            if(tick>0)
            {
                System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);
            }
        }
    }
}


class  TicketDemo
{
    public static void main(String[] args) 
    {

        Ticket t = new Ticket();

        Thread t1 = new Thread(t);//创建了一个线程;
        Thread t2 = new Thread(t);//创建了一个线程;
        Thread t3 = new Thread(t);//创建了一个线程;
        Thread t4 = new Thread(t);//创建了一个线程;
        t1.start();
        t2.start();
        t3.start();
        t4.start();    
    }
}

两种方式的区别:

第二种方式好处:避免了单继承的局限性。比如当一个student类继承了person类,再需继承其他的类时就不能了,所以在定义线程时,建议使用第二种方式。

解决多线程安全性问题:1、同步代码块

                                 2、同步函数:锁为this

                                 3、静态同步函数:   锁为Class对象:类名.class

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值