黑马程序员:多线程

来源:互联网 发布:matlab解矩阵方程ax=b 编辑:程序博客网 时间:2024/06/05 19:06

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

线程:
就是进程中的一个独立的控制单元,线程在控制进程的执行(多对一,进程有很多线程)。

创建线程方法1:
class Demo extends Thread{//1.继承Thread类
   Demo(String name){
      super(name);//定义线程的名字,有默认的(数字)
   }
   public void run(){//复写run()方法,用来存储线程运行的代码,同main方法一样。
      System.out.println(Thread.currentThread().getName()+"run....");//和下同
      System.out.println(this.getName()+"run....");//父类中得来的线程名 
   }
}
实例化后调用start()方法启动:
Demo demo=new Demo("myThread");//加入线程名字,默认从0开始
demo.start();//开启线程并且运行run()方法



创建线程方法2:
class Ticket implements Runnable{//实现接口,thread要的就是run()方法式复写
   private int tickets=100;
   public void run(){
      while(true){
         if(tickets>0)
 System.out.println(this.getName+":"+tickets--);
      }
   }
}
实例化后,加入到Thread实体线程中,再start()方法启动:
Ticket t=new Ticket();
Thread thread1=new Thread(t);//接口子类加入Thread构造方法中来指定run()
Thread thread2=new Thread(t);
thread1.start();
thread2.start();



区别:用接口更加灵活,继承了别的类,就不能用 Thread继承了。

JAVA对于多线程的安全问题(票会变成负数),解决方法:
synchronized(对象){
   需要被同步的代码(主要考虑共享的东西)
}
例子改动:
class Ticket implements Runnable{
   private int tickets=100;
   public void run(){// 也可在这加synchronized :public synchronized void run(){...}
      while(true){
         synchronized(Ticket.class){// 同步,意另一个线程到这时,将会等待此完成后执行
         if(tickets>0){
 try{Thread.sheep(10);}catch(Exception e){}
 System.out.println(this.getName+":"+tickets--);
            }
         }
      }
   }
}




线程运行状态:
1.start()
2.sleep(time)时间一到回到运行
3.wait()例:程序死了,进程还活着,一直等,用notify()回到运行,旁边人叫醒
4.stop()和进程结束一样。
运行:2和3没有执行资格>冻结,有执行资格加上CPU执行权才运行。


原创粉丝点击