创建线程继承Thread和实现Runnable接口
继承Thread类
在java中如何创建线程:
1、继承Thread类;
线程类:只有Thread类或者Thread类的子类
1.写个类A继承java。lang。Thread类
2.在类A中重写Thread中的run()方法
3.在run()中写需要执行的操作,run()里面的代码---线程执行体
4.在main方法中,启动线程--创建线程对象,调用start()方法。
A a=new ();
a.start();
不是调用run(),如果调run,好比是对象调方法,
程序中还是只有一条主线程。
下面是例子:
package com.briup.day18;
/*
* 50个苹果,找三位同学,将Student类定义成线程(把每一位同学当做是一条线程)
*/
public class AppleDemo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s1 = new Student("A");
Student s2 = new Student("B");//由于下面只有有参构造器,所以这里必须要有具体的名字,这的A是线程的名字,另外注意和实现Runnable时起名字是不同的
Student s3 = new Student("C");
s1.start();
s2.start();
s3.start();
}
}
class Student extends Thread{
private int count = 50;
public Student(String name){
super(name);
}
@Override
public void run(){
for(int i = 50;i>0;i--){
System.out.println(getName()+"吃苹果" +count--);
}
}
}
2、实现Runnable接口:
1.写个类A实现Runnable接口;类A不是线程类。
2.覆盖接口中的run方法
3.在run()中写需要执行的操作,run()里面的代码---线程执行体
4.在main方法中,启动线程--创建线程对象,调用start()方法。
创建线程类对象:
Thread thread=new Thread(new A());
启动线程:
thread.start();//一定是线程调用方法
可以分开写:
A a = new A();
Thread thread = new Thread(a);
thread.start();
package com.briup.day18;
public class AppleDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Apple a =new Apple();
Thread thread1 = new Thread(a,"A");//注意这里给线程起名字
Thread thread2 = new Thread(a,"B");
Thread thread3 = new Thread(a,"C");
thread1.start();
thread2.start();
thread3.start();
}
}
class Apple implements Runnable{
private int appleCount = 50;
public void run(){
for(int i=0;i<50;i++){
if(appleCount>0){
//获得线程的名字同样需要线程来调度
System.out.println(Thread.currentThread().getName()+"吃苹果 "+appleCount--);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3 、通过匿名内部类实现
在某一个对象只是用一次的时候会出现