——- android培训、java培训、期待与您交流! ———-
相关概念
线程:就是进程中一个独立的控制单元,线程就在控制着进程的执行,一个进程至少有一个线程。
多线程的好处:解决了多部分代码同时运行的问题。
多线程的弊端:线程太多,会导致效率的降低。
调用线程的方法
1,定义类继承Thread
2,复写Thread类中的run方法
3,调用线程的start方法
class Demo extends Thread{
private String name ;
Demo(String name){
this.name = name;
}
public void run(){
for(int x = 0; x < 10; x++){
System.out.println(name + "...x=" + x + "...ThreadName=" +
Thread.currentThread ().getName());
}
}
}
class ThreadDemo{
public static void main(String[] args){
Demo d1 = new Demo(" lihua ");
Demo d2 = new Demo("xiaoqiang");
d1.start(); // 开启线程,调用 run 方法。
d2.start();
for(int x = 0; x < 20; x++){
System.out.println("x = " + x + "...over..." +
Thread.currentThread().getName());
}
}
}
实现Runnable方法
1,定义类实现Runnable接口
2,覆盖Runnable接口中的run方法,将线程要运行的代码存放在该run中
3,通过Thread类建立线程对象
4,将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数,为什么要讲 Runnable接口的子类对象传递给Thread的构造函数,因为,自定义的run方法所 属 的对象是Runnable接口的子类对象,所以要让那个线程去执行指定对象的run方法, 就必须明确该run方法所属对象
5,调用Thread类的start方法开启线程并调用Runnable接口子类的run方法。
class Demo implements Runnable{
public void run(){ //复写Runnable中run()方法
show();
}
public void show(){
for(int x = 0; x < 20; x++){
System.out.println(Thread.currentThread().getName() + "..." + x);
}
}
}
class ThreadDemo{
public static void main(String[] args){
Demo d = new Demo();
Thread t1 = new Thread(d); //调用Runnable的实现类
Thread t2 = new Thread(d);
t1.start();
t2.start();
}
}