多线程程序
- Java在语言级提供了对多线程程序设计的支持
- 实现多线程程序的两种方式:
- 从Thread类继承;(file 1,file2)
- 实现Runnable接口;(file 3) 大多数情况下,如果只想重写 run() 方法,而不重写其他 Thread 方法,那么应使用 Runnable 接口;
- Java运行时系统实现了一个用于调度线程执行的线程调度器,用于确定某一时刻由哪一个线程在CUP上运行;
- 在Java技术中,线程通常是抢占式的而不需要时间片分配进程。抢占式调度模型就是许多线程处于可以运行状态(等待状态),但实际上只有一个线程在运行,该线程一直运行到它终止进入可运行状态(等待状态),或者另一个具有更高优先级的线程变成可运行状态。在后一种情况下,低优先级的线程被高优先级的线程强占,高优先级的线程获得运行的机会;
- Java线程调度器支持不同优先级线程的抢先方式,但其本身不支持相同优先级线程的时间片轮换;
- Java运行时系统所在的操作系统支持时间片的轮换,则线程调度器就支持相同优先级线程的时间片轮换;
## file 1 ##
class MulThread{
public static void main(String[] args){
MyThread mt = new MyThread();
mt.start();
System.out.println("main="+Thread.currentThread().getName());
}
}
class MyThread extends Thread{
public void run(){
System.out.println(getName());
}
}
## file 2 ##
class MulThread{
public static void main(String[] args){
MyThread mt = new MyThread();
mt.setDaemon(true);
mt.start();
int index = 0;
while(true){
if(index++ == 1000){
break;
}
System.out.println("main="+Thread.currentThread().getName());
}
}
}
class MyThread extends Thread{
public void run(){
while(true)
System.out.println(getName());
}
}
## file 3 ##
class MulThread{
public static void main(String[] args){
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.setDaemon(true);
t.start();
int index=0;
while(true){
if(index++==1000)
break;
System.out.println("main="+Thread.currentThread().getName());
}
}
}
class MyThread implements Runnable{
public void run(){
while(true){
System.out.println(Thread.currentThread().getName());
}
}
}