您的位置:首页 > 其它

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

2015-05-14 21:01 736 查看
第一种方式:继承Thread类

步骤:1、定义类继承Thread

2、覆写Threa类的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐