线程基础

—、线程基础知识
  • 线程:程序中不同的执行路径
  • 进程:一个静态的程序
    cpu由于运行很快,所以将时间片分给多个线程,这样看起来就像是并行执行
  • 多进程:在操作系统中能够同时运行多个任务(程序)
  • 多线程:在同一应用程序中有多个顺序流同时执行
  • 创建线程的两种方法:
    1)Runnable接口
    2)继承Thread类
    一般使用Runnable接口,因为这样可以继承其他类
    线程状态转换
二、线程控制的几种方法

线程控制的几种方法:sleep、join、yield、priority

sleep阻塞线程:

代码举例:

public class Threaddemo1 {

	public static void main(String[] args) {
		Runner1 r = new Runner1();
		r.start();
		try
		{
			Thread.sleep(10000);
		}catch (InterruptedException e) {
		}
        //中断线程
		r.interrupt();
	}
}

class Runner1 extends Thread{
	public void run() {
		while (true) {
			System.out.println("------");
           //sleep阻塞一定要捕获异常
			try {
				Thread.sleep(1000);
			}catch (InterruptedException e) {
				return;
			}
					
		}
		
	}
	
}

join合并线程:

代码举例:

//join()合并线程
public class Threaddemo2 {
        public static void main(String[] args) {
		// TODO Auto-generated method stub
		Mythread t1 = new Mythread("xs");
		t1.start();
		//合并线程,t1合并到主线程,只有当t1完成了才继续执行主线程
		//问题:为什么一定要try抛出异常
		try {
			t1.join();
		}catch (InterruptedException e) {
			// TODO: handle exception
		}
		for (int i = 0; i < 10; i++) {
			System.out.println("i am main thread"+i);
		}
	}
}
class Mythread extends Thread{

	public Mythread(String s) {
		super(s);
	}
	
	public void run() {
		for (int i = 0; i <10; i++) {
			System.out.println("i am "+getName());
		}
		try {
			sleep(1000);
		}catch (InterruptedException e) {
			// TODO: handle exception
			return;
		}
	}
}

yield:
代码举例:

//yield让出cpu,让其他线程执行机会,但是不是让其他线程全部执行完,而是给出一点时间
public class Threaddemo3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Mythread1 t1 = new Mythread1("xs");
		Mythread1 t2 = new Mythread1("qq");
		t1.start();
		t2.start();
        }
}

class Mythread1 extends Thread{
	public Mythread1(String s) {
		// TODO Auto-generated constructor stub
		super(s);
		}
	
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(getName()+i);
			if (i%10==0) {
				yield();
			}
		}
	}
}

priority增加线程优先级:

//增加线程的优先级
public class Threaddemo4 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread t1 = new Thread(new Mythread3());
		Thread t2 = new Thread(new Mythread4());
		t1.setPriority(Thread.NORM_PRIORITY + 5);
		t1.start();
		t2.start();
        }
}
class Mythread3 implements Runnable{
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("t1"+i);
		}
	}
}
class Mythread4 implements Runnable{
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("t2:"+i);
		}
	}
}

posted @ 2019-07-22 21:52  喜欢佩琦的程序猿  阅读(96)  评论(0编辑  收藏  举报