一、基本概念
- 进程:是一个静态的概念,当程序要执行的时候会将代码放到代码区,这时程序还未执行,但已经有了一个进程。
- 一个进程里有多个线程,也就是多条执行路径,但一定有一条主线程,就是main方法。注意区别线程和函数调用的区别
- 在一个时间点上,cpu只能运行一个线程(只是速度很快,看起来像是多线程,真正的多线程是双核,双cpu)
二、线程创建与启动
- run方法:定义线程的具体内容;start方法:启动线程
- 两种创建线程方法:
- 定义新的线程类实现Runnable接口,必须实现里面唯一的方法run方法
- 定义线程子类继承Thread类
- 启动线程:start();
public class TestThread {
public static void main(String args[]){
/* testRunnable r=new testRunnable();
Thread t1=new Thread(r);
t1.start();
*/
r.run();
for(int i=0;i<3;i++){
System.out.println("mainThread:"+i);
}
}
}
class testRunnable implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<3;i++)
{
System.out.println("thread:"+i);
}
}
}
上面的示例代码中,由于没有创建Thread对象,没有start线程,r.run()方法相当于方法调用,而不是线程运行,要想启动线程,只有start方法。执行过程如下,run方法和for循环顺序执行:
结果为:thread:0
thread:1
thread:2
mainThread:0
mainThread:1
mainThread:2
如果将run方法注释掉,变成现在注释中的内容,就相当于又创建了一个子进程,cpu交替分配时间片,和main进程交替进行,执行过程如下:
![]()
运行结果如下:mainThread:0
thread:0
thread:1
mainThread:1
mainThread:2
thread:2
注意:每次运行结果不一样
三、线程状态图
就绪调度阻塞说明线程都活着,只有终止了,线程就死了。并且当启动一个线程后,不会立即执行,会先排队
四、常用的方法
- join()方法:即合并
public class testJoin { public static void main(String args[]){ subThread s1=new subThread(); s1.start(); try { s1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block return; } for(int i=0;i<3;i++){ System.out.println("mainThread:"+i); } } } class subThread extends Thread{ public void run(){ for(int i=0;i<3;i++){ System.out.println("subThread:"+i); try{ sleep(10000);} catch(InterruptedException e){ interrupt(); } } } }
以上代码,如果不加s1.join方法,就是主线程和子线程交替运行,加上.join方法后,就变成了函数调用,子线程执行完了,返回主线程继续执行
结果subThread:0
subThread:1
subThread:2
mainThread:0
mainThread:1
mainThread:2
- sleep():睡眠
- yeild:让出cpu
public class testYield { public static void main(String args[]){ MyThread3 m=new MyThread3("m"); MyThread3 t=new MyThread3("t"); m.start(); t.start(); } } class MyThread3 extends Thread{ MyThread3(String s){ super(s); } public void run(){ for(int i=1;i<10;i++){ System.out.println(this.getName()+i); if(i%4==0) yield(); } } }
- 优先级相关方法