package LyfPractice;
/**
* Created by fangjiejie on 2016/12/6.
*/
/*
线程是程序内的控制流。
多线程:在同一个应用程序中的多个顺序流(任务)同时执行
多进程:在操作系统能同时运行多个任务(程序,软件)
线程:
1.主线程:在主方法中,串行运行
2.用户线程
*/
public class H {
public static void main(String[] args) {
/*用户线程的两次调用
new H1().run();
new H1().run();
System.out.println();*/
//多线程
H1 m1=new H1();
H1 m2=new H1();
m1.setName("m1号线程");//设置线程的新名字
m2.setName("m2号线程");
m1.start();//多线程用start启动线程核心方法run
m2.start();
}
}
//第一种方法:直接创建多线程类
class H1 extends Thread{//继承了Thread后,成为多线程类
@Override
public void run() {
super.run();
for(int i=0;i<1000;i++){
//获取线程名字的两种方法:
//System.out.print(this.getName()+": ");
System.out.print(Thread.currentThread().getName()+": ");
System.out.println(i);
}
}
}
package LyfPractice;
/**
* Created by fangjiejie on 2016/12/15.
*/
//第二种方法:创建一个直接实现Runnable的类,再借助Thread类来启动线程
//Thread 类实现了Runnable 接口,来创建线程
public class K {
public static void main(String[] args) {
K1 k=new K1();//K1实现了Runnale接口
Thread h=new Thread(k);//但还是需要借助Thread类来启动线程
h.start();
}
}
class K1 implements Runnable{
@Override
public void run() {
for(int i=0;i<1000;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
//第三种的方法:匿名内部类(和第二种性质相同哦)
class P{
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}).start();
}
}
/两大类线程启动方式比较:/
通常情况下,我们还是建议使用前面的方法,可以避后面方法只能单继承的缺陷。