JAVA中的线程 学习笔记

概念:

1、JAVA多线程机制:不同线程之间的快速切换

2、程序:静态代码

3、进程:一次程序的动态执行过程

4、线程:比进程更小的执行单位

5、线程对象:用Thread及其子类表示

多线程:

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Print1 pri1 = new Print1();
		Print2 pri2 = new Print2();
		pri1.start();
		pri2.start();
		for(int i = 1; i <= 15; i++)
		{
			System.out.print("first" + " ");
		}
	}

}

public class Print1 extends Thread{
	public void run() {
		for(int i = 1; i <= 15; i++)
		{
			System.out.print("second" + " ");
		}
	}
}

public class Print2 extends Thread{
	public void run(){
		for(int i = 1; i <= 15; i++)
		{
			System.out.print("third" + " ");
		}
	}
}

运行结果(每次运行结果不同):

second second third third third third third third third third third third third third third third third first first first first first first first first first first first first first first first second second second second second second second second second second second second second 

6、线程调度优先级:分为 1 - 10,默认为 5,.setPriority(int gread) 用来设定线程的优先级,优先级高的始终执行,相同的轮流执行,设置优先级不在 1 - 10 会产生 lllegalArgumenException 异常。

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Print1 pri1 = new Print1();
		Print2 pri2 = new Print2();
		pri1.start();
		pri2.start();
        pri1.setPriority(10);
		for(int i = 1; i <= 15; i++)
		{
			System.out.print("first" + " ");
		}
	}

}

public class Print1 extends Thread{
	public void run() {
		for(int i = 1; i <= 15; i++)
		{
			System.out.print("second" + " ");
		}
	}
}

public class Print2 extends Thread{
	public void run(){
		for(int i = 1; i <= 15; i++)
		{
			System.out.print("third" + " ");
		}
	}
}

 上述代码虽然调高了pri1的优先级,但是并不是pri1执行完之后才会执行其它线程,原因如下:

优先级高的线程可以获得优先调度过,调度以时间片为单位。 不是说优先级高的线程运行完了才能调度优先级低的线程。

应用:用 Thread 的子类创建线程,所有线程共用一个对象,使结果尽量不依赖当前 CPU 资源的说哦用状况:

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StringBuffer str = new StringBuffer();
		Print1 pri1 = new Print1("张三", str);
		Print1 pri2 = new Print1("李四", str);
		pri1.start();
		pri2.start();
		//pri1.setPriority(10);
	}

}

public class Print1 extends Thread{
	StringBuffer str;
	Print1(String s, StringBuffer str) {
		this.str = str;
		setName(s);//为线程起名
	}
	public void run() {
		for(int i = 1; i <= 3; i++)
		{
			str.append(getName() + " ");
			System.out.println("我是" + str);
			try {
				sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}//sleep中断 200ms ,切换进程
		}
	}
}

 

你可能感兴趣的:(学习笔记,JAVA多线程)