1. 使用继承Thread
package mypack;
public class Demo1 extends Thread
{
private String name ;
public Demo1(final String name)
{
this.name = name;
}
public void show()
{
for(int x = 0 ; x < 10 ; x++)
{
System.out.println( name + " ........... " + x);
}
}
public void run() //重写父类Thread的run方法
{
show();
}
}
/*
使用Thread继承方法的坏处:
1. Demo1是继承Thread的,如果Demo1还想继承其他类(比如Person类),以便获取到其他类的一些资源,就不行了
因为Java是单继承的, 不允许public class Demo1 extends Thread,Person
2. 各自的线程资源是独立的, 不便于共享,比如买票系统中的票是各个对象共享的,使用Thread继承方法无法实现
资源共享
*/
import mypack.Demo1;
class ThreadDemo1
{
public static void main(String[] args)
{
Demo1 demoa = new Demo1("zhangsan");
Demo1 demob = new Demo1("lisi");
// demoa.show();
// demob.show();
// demoa.run();
// demob.run();
demoa.start(); //开启线程,调用线程的任务run方法
demob.start();
System.out.println(" Hello World !!!");
}
}
2. 使用实现Runnable
package mypack;
public class Demo2 implements Runnable
{
private String name ;
public Demo2(final String name)
{
this.name = name;
}
public void show()
{
for(int x = 0 ; x < 10 ; x++)
{
System.out.println( name + " ........... " + x);
}
}
public void run() //实现Runnable接口的run方法
{
show();
}
}
/*
1. Runnable方法是实现接口, Demo2只是实现Runnable中的接口,并不是Runnable中的子类
2. Runnable仅仅将线程的任务进行了对象的封装,Thread也实现了Runnable接口,然后再扩充
自己的内容
3. 继承Thread类是覆盖父类Thread的run方法,实现Runnable接口是覆盖Runnable的run方法;
*/
import mypack.Demo2;
class ThreadDemo2
{
public static void main(String[] args)
{
Demo2 demoa = new Demo2("zhangsan");
Demo2 demob = new Demo2("lisi");
Thread t1 = new Thread(demoa);
Thread t2 = new Thread(demob);
t1.start(); //开启线程,调用线程的任务run方法
t2.start();
System.out.println(" Hello World !!!");
}
}