线程是进程中用于控制程序执行的控制单元,进程中至少有一个线程。进程中至少一个线程负责java程序的执行。这个线程运行的代码存在于main方法中,为主线程
该线程称之为主线程。
创建线程有两种方式
一.继承Thread类,复写run()方法。
1.定义类继承Thread类。
2.复写run()方法。
3.调用线程的start()方法。
public class MyThread extends Thread
{
public void run()
{
for(int x=0; x<50; x++)
System.out.println("MyThread----"+x);
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
MyThread d = new MyThread();//创建一个线程。
d.start();//开启线程并执行该线程的run方法。
//d.run();//仅仅是对象调用方法。而线程创建了,并没有运行。
for(int x=0; x<50; x++)
System.out.println("main--"+x);
}
}
二.实现Runnable接口,复写run()方法。1.定义类实现Runnable接口。2.覆盖Runnbale接口中的run()方法。3.通过Thread类建立线程对象。4.将Runnable接口的子类对象作为参数传递给Thread类的构造函数。
5.调用Thread类的start()方法开启线程,并调用Runnable接口子类的run方法。
public class MyThread implements Runnable{
public void run(){
for(int x=0; x<50; x++)
System.out.println("MyThread----"+x);
}
}
public class MyThread{
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread());t1.start();
for(int x=0; x<50; x++)
System.out.println("main--"+x);
}
}
三、两种方式的特点:
实现方式,因为避免了单继承的局限性,所以创建线程建议使用第二种方式。