线程

一、基本概念

  • 进程:是一个静态的概念,当程序要执行的时候会将代码放到代码区,这时程序还未执行,但已经有了一个进程。
  • 一个进程里有多个线程,也就是多条执行路径,但一定有一条主线程,就是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();
		}
	}
}
  • 优先级相关方法

转载于:https://my.oschina.net/kongjunli/blog/742707

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值