创建线程的方法有两种方法
1.利用Thread类的子类来创建线程
2.利用Runnable接口来创建线程
Thread类的构造方法有:
public Thread(); //使用这个构造方法必须创造一个子类,并且覆盖run()方法
public Thread(String name);//name是指定线程的名字
public Thread(Runnable target); //target的run()方法将被线程对象调用
public Thread(Runnable target,String name) //不仅target的run()方法将被线程调用,而且线程的名字也将被name指定
Thread类里的常用方法
public static Thread currentThread();//返回当前正在运行的线程对象
public final String getName();//返回线程的名字
public void start();//将线程由新建状态变为就绪状态
public void run();//线程执行的任务
public final boolean isAlive();//当前的线程是否在运行,是就返回true,不是就返回false
public static boolean isInterrupted();//判断线程是否被中断,是就返回true,不是就返回false
public final void join();//暂停当前线程的运行,直到调用该方法的线程运行结束在继续运行
public final int getPriority();//返回线程的优先级
public final void setPriority(int newPriority)// 设置线程的优先级
public static void sleep(long millis);//为当前线程指定睡眠时间
public static void yield();//暂停当前线程的运行,但是该线程仍然处于就绪状态,不转为阻塞状态,该方法只给同优先级线程以运行的机会
Thread类创建线程的步骤:
1.子类继承Thread类
2.线程所要执行的代码都写在run()方法内
package practice4;
class MyThread1 extends Thread{
private String who;
public MyThread1(String str){
who=str;
}
public void run(){
for(int i=0;i<5;i++){
try {
sleep((int)(1000*Math.random()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(who+i+"正在运行!!!");
}
}
}
public class App11_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread1 you=new MyThread1("你");
MyThread1 she=new MyThread1("她");
you.start();
try {
you.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
she.start();
try {
she.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("主方法main()运行结束!!!");
}
}
Runnable接口中只有一个方法run(),用户可以声明一个类并实现Runnable接口,然后重新定义run()方法,将线程代码写入其中,就完成了这一部分的任务。但是Runnable接口并没有任何对线程的支持,还必须创建Thread的实例,可以通过Thread的构造方法来实现
package practice4;
class MyThread implements Runnable{
private String who;
public MyThread(String str){
who=str;
}
public void run(){
for(int i=0;i<5;i++){
try {
Thread.sleep((int)(1000*Math.random()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(who+"正在运行!!");
}
}
}
public class App11_2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread you =new MyThread("你");
MyThread she =new MyThread("她");
Thread t1=new Thread(you);
Thread t2=new Thread(she);
t1.start();
t2.start();
}
}
两种创建线程的方式的特点:
直接继承Thread类的特点:编写简单,可以直接操作线程,缺点是一当继承了Thread类,则既不能继承其他的类
Runnable接口的特点是:可以将Thread和要处理的任务的类分开,形成清晰的模型。在Thread类中的this即指当前进程,而在Runnable接口中,只能通过Thread.currentThread()方法。