1、继承Thread类
子类覆写父类中的run方法,将线程运行的代码存放在run中。
建立子类对象的同时线程也被创建。
通过调用start方法开启线程。
2、实现Runnable接口
子类覆盖接口中的run方法。
通过Thread类创建线程,并将实现了Runnable接口的子类对象作为参数传递给Thread类的构造函数。
Thread类对象调用start方法开启线程。
可使用匿名内部类来写
package july7; //线程的两种方法
class MyThread extends Thread{
private String name;
public MyThread(String name) { super(); this.name = name; }
public void run(){System.out.println(name+"启动!"); }
}
class YourThread implements Runnable{
private String name;
public YourThread(String name) { this.name = name; }
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName()+"第"+i+"次启动!"); }}}
public class Demo1 {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
if(i == 50){
new MyThread("li").start();
new Thread(new YourThread(""),"xiatian").start();
}
}
}
}
Thread类中run()和start()方法的区别如下:
run()方法:在本线程内调用该Runnable对象的run()方法,可以重复多次调用;
start()方法:启动一个线程,调用该Runnable对象的run()方法,不能多次启动一个线程;
两种进程创建方式比较
A extends Thread:(简单) 、不能再继承其他类了(Java单继承)、同份资源不共享
A implementsRunnable:(推荐) 、多个线程共享一个目标资源,适合多线程处理同一份资源。
该类还可以继承其他类,也可以实现其他接口。
package july7;
//线程卖票的例子
class SellTicket extends Thread{
private String name;
private int num = 50;
public SellTicket(String name) {
super();
this.name = name;
}
public void run(){
for (int i = 1; i <=num; i++) {
System.out.println(name+"卖出了第"+i+"张票!");
}
}
}
class MySell implements Runnable{
private int num = 50;
@Override
public void run() {
for (int i = 1; i <=num; i++) {
System.out.println(Thread.currentThread().getName()+"卖出了第"+i+"张票!");
}
}
}
public class Demo2 {
public static void main(String[] args)throws Exception {
new SellTicket("A").start();
new SellTicket("B").start();
new SellTicket("C").start();
new Thread(new MySell(),"D").start();
new Thread(new MySell(),"E").start();
new Thread(new MySell(),"F").start();
for (int i = 10; i > 0; i--) {
System.out.println(i);
Thread.sleep(1000);
}
}
}