线程
进程:程序一次执行过程,需要经历代码加载、代码执行的执行完毕的一个完整的过程
java的多线程可以运行多个程序块,是程序的运行效率提高,克服传统线程语序无法解决的问题
线程的运行需要本机操作系统的支持
Thread类:如果一个类继承了Thread类那么只能调用一次start方法,如果多次调用就会抛出IllegalThreadStateException。如果一个类继承了Thread类,则不适合于多个线程共享资源。实现Runnable接口,就可以方便的实现资源共享。
要不使用Runnable接口,那我们来看下回有什么问题:
one.继承类Thread
1 package Threadclass; 2 3 /* 4 * 继承类不能资源共享 5 * 6 * */ 7 8 public class third extends Thread{ 9 private int ticket = 5; //一共5张票 10 11 12 //覆盖Run方法,实现票信息的输出 13 public void run(){ 14 for(int i = 0 ;i<10;i++){ 15 if(ticket>0)System.out.println("买票 :ticket"+ticket--); 16 } 17 } 18 public static void main(String[] args) { 19 third one = new third(); //定义one线程对象 20 third two = new third(); //定义two线程对象 21 third third = new third(); //定义two线程对象 22 one.start(); //启动线程 23 two.start(); //启动线程 24 third.start(); //启动线程 25 } 26 }
1 买票 :ticket5 2 买票 :ticket5 3 买票 :ticket5 4 买票 :ticket4 5 买票 :ticket4 6 买票 :ticket3 7 买票 :ticket4 8 买票 :ticket2 9 买票 :ticket3 10 买票 :ticket1 11 买票 :ticket3 12 买票 :ticket2 13 买票 :ticket2 14 买票 :ticket1 15 买票 :ticket1
要是电影院开了三个窗口,要是按照票数一定,那么这种卖票方式一定是不对的,这也就是说程序中启用了三个线程,但是三个线程都分别卖了5票,并没有达到资源共享。
two。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package Rubbableclass; 2 3 public class two { 4 class MyRunnable implements Runnable{ 5 private int ticket; 6 public MyRunnable() { 7 // TODO 自动生成的构造函数存根 8 ticket = 5; 9 } 10 @Override 11 public void run() { 12 // TODO 自动生成的方法存根 13 for(int i = 0 ;i<10;i++){ 14 if(ticket>0){ 15 System.out.println("卖票:"+ticket--); 16 } 17 } 18 19 } 20 21 } 22 23 public static void main(String[] args) { 24 // TODO 自动生成的方法存根 25 MyRunnable Run_one = new two().new MyRunnable(); 26 MyRunnable Run_two = new two().new MyRunnable(); 27 Thread one = new Thread(Run_one); 28 Thread two = new Thread(Run_one); 29 Thread third = new Thread(Run_two); 30 one.start(); 31 two.start(); 32 third.start(); 33 } 34 35 }
卖票:5 卖票:4 卖票:3 卖票:2 卖票:1 卖票:5 卖票:4 卖票:3 卖票:2 卖票:1
可以看出启动了2个线程但是一个才卖了5张票,及被共享了,所以实现接口有:
1.适合多个相同程序代码的线程去处理同一资源。
2.可以避免由于java的单继承性带来的局限
3.增强了程序,代码能被多个线程共享,代码与数据是独立的。
start()在Thread中的定义:public synchronized void start(){
if(threadStart!=0)throw new IllegalThreadStateException();
.....
start0();
.......
}
private native void start0();