Java 多线程教学课件.ppt

Java 多线程教学课件.ppt

ID:60988974

大小:1.01 MB

页数:66页

时间:2021-01-17

上传者:U-189834
Java 多线程教学课件.ppt_第1页
Java 多线程教学课件.ppt_第2页
Java 多线程教学课件.ppt_第3页
Java 多线程教学课件.ppt_第4页
Java 多线程教学课件.ppt_第5页
资源描述:

《Java 多线程教学课件.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

7.Java多线程 2021/9/212内容多线程基本概念Java多线程创建多线程线程的状态控制Java多线程的一些问题小结注:本课件部分材料来自网络 2021/9/2131多线程基本概念文件输入输出装置各种系统资源数据区段程序区段只有一个地方在执行文件输入输出装置各种系统资源数据区段程序区段同时有数个地方在执行传统的进程多线程的任务 2021/9/214多线程的优势:减轻编写交互频繁、涉及面多的程序的困难程序的吞吐量会得到改善由多个处理器的系统,可以并行运行不同的线程(否则,任何时刻只有一个线程在运行,形成并发运行) 2021/9/215线程与进程的区别:多个进程的内部数据和状态都是完全独立的,而多线程是共享一块内存空间和一组系统资源,有可能互相影响线程本身的数据通常只有寄存器数据,以及一个程序执行时使用的堆栈,所以线程的切换比进程切换的负担要小 多线程编程原则安全性:如果两个以上的线程访问同一对象时,一个线程会损坏另一个线程的数据,这就违反了安全性原则可行性:如果仅仅实现了安全性,程序却在某一点后不能继续执行或者多个线程发生死锁,那么这样的程序也不能作为真正的多线程程序来应用高性能:多线程的目的是为了增加程序运行的性能2021/9/216 2021/9/2172.Java线程概念对线程的综合支持是Java技术的一个重要特色.它提供了thread类、监视器和条件变量的技术.虽然许多操作系统支持多线程,但若要用C或C++编写多线程程序是十分困难的,因为它们对数据同步的支持不充分. 线程对象和线程的区别:线程对象是可以产生线程的对象比如在java平台中Thread对象,Runnable对象。线程,是指正在执行的一个指令序列。在java平台上是指从一个线程对象的start()开始,运行run方法体中的那一段相对独立的过程。2021/9/218 思考如果我们成功编译了该java文件,然后运行发生的过程…Jvm进程启动,JVM产生一个主线程还有一些其它线程,例如垃圾回收等2021/9/219classBeginClass{publicstaticvoidmain(String[]args){for(inti=0;i<100;i++)System.out.println("Hello,World!");}} 剖析多线程程序2021/9/2110classMyThreadextendsThread{publicvoidrun(){System.out.println("Threadsay:Hello,World!");}}publicclassMoreThreads{publicstaticvoidmain(String[]args){newMyThread();newMyThread().start();System.out.println("Mainsay:Hello,World");}} 2021/9/21113.创建多线程Runnable与Thread1.publicclassmythreadextendsAppletimplementsRunnable(小应用或已经是某个类的子类时)2.继承类ThreadpublicclassmythreadextendsThread创建方法:newthread=newThread(this);newthread.start(); 2021/9/2112Runable与Thread的区别使用runable最主要的原因是:java缺少多重继承的机制,可能你的类已经继承了其他类了,这时你无法继承自thread类,只能用runnable了Runable创建的线程共享数据区 publicclassTest{publicstaticvoidmain(String[]args)throwsException{MyThreadmt=newMyThread();mt.start();mt.join();Thread.sleep(3000);mt.start();}}输出:Exception in thread "main" java.lang.IllegalThreadStateException说明:通过Thread实例的start(),一个Thread的实例只能产生一个线程2021/9/2113 2021/9/2114classRimplementsRunnable{privateintx=0;publicvoidrun(){for(inti=0;i<100;i++){try{Thread.sleep(10);}catch(Exceptione){}System.out.println(x++);}}}publicclassTest{publicstaticvoidmain(String[]args)throwsException{Rr=newR();for(inti=0;i<10;i++)newThread(r).start();}} 2021/9/2115packagedebug;importjava.io.*;importjava.lang.Thread;classMyThreadextendsThread{publicintx=0;publicvoidrun(){System.out.println(++x);}}classRimplementsRunnable{privateintx=0;publicvoidrun(){System.out.println(++x);}}publicclassTest{publicstaticvoidmain(String[]args)throwsException{for(inti=0;i<10;i++){Threadt=newMyThread();t.start();}Thread.sleep(10000);//让上面的线程运行完成Rr=newR();for(inti=0;i<10;i++){Threadt=newThread(r);t.start();}}} 2021/9/2116重要的方法start()从CPU中申请另一个线程空间来执行run()方法中的代码run()是运行线程的主体,启动线程时,由java直接调用publicvoidrun()如果你不调用Start,直接调用run,会如何?stop()停止线程,调用线程的newthread.stop()(不是安全的处理)sleep方法暂停线程的执行,让其它线程得到机会,sleep要丢出异常,必须抓住:Try{sleep(100)}catch(InterruptedExceptione){} 2021/9/2117importjavax.swing.*;publicclassApplet1extendsJApplet{mythreadt1=newmythread();publicvoidinit(){t1.start();}classmythreadextendsThread{publicvoidrun(){for(inti=0;i<4;i++)System.out.println(""+i);{try{sleep(400);}catch(InterruptedExceptione){}}}}} 2021/9/21187.2创建线程的方式importjavax.swing.*;importjava.awt.*;publicclassApplet1extendsJApplet{Ct1=newC(this);publicvoidinit(){t1.start();}publicvoidpaint(Graphicsg){g.drawString("Hello,java",10,50);}}classCextendsThread{Applet1a;C(Applet1b){a=b;}publicvoidrun(){while(true){a.repaint();try{sleep(400);}catch(InterruptedExceptione){}}}} join:等待线程执行完毕,被等待的那个线程不结束,当前线程就一直等待.2021/9/2119publicclassTest{publicstaticvoidmain(String[]args)throwsException{MyThreadmt=newMyThread();mt.start();mt.join();System.out.println(101);}} 2021/9/2120其它常用的方法isAlive:判断线程目前是否正在执行状态中if(newthread.isAlive())newthread.stop();resume:要求被暂停线程继续执行suspend:暂停线程的执行yield:将执行的权力交给其它线程,自己到队列的最后等待. 2021/9/2121线程的优先权某一时刻只有一个线程在执行,调度策略为固定优先级调度.newthread.setPriority(Thread.MIN_PRIORITY)级别有:MIN-PRIORITYNOM_PRIORITYMAX-PRIORITY自私的线程:有很高的优先权的线程,不主动睡眠或让出处理器控制权. 2021/9/21224.线程的状态控制newThread()NewThreadRunnablestart()NotRunnablestop()stop()Deadyield()stop()orrun()exit..suspend()sleep()wait()resume().线程的状态 2021/9/2123当一个线程执行完所有语句后就自动终止调用线程的stop()方法,也可以强制终止线程,可能产生不完整的残废数据。如果希望线程正常终止,可采用标记来使线程中的run()方法退出 2021/9/2124publicclassXyzimplementsRunnable{privatebooleantimeToQuit=false;publicvoidrun(){while(!timeToQuit){…..}//cleanupbeforerun()ends;}publicvoidstopRunning(){timeToQuit=true;}} 2021/9/2125publicclassControlThread{privateRunnabler=newXyz();privateThreadt=newThread(r);publicvoidstartThread(){t.start();}publivoidstopThread(){r.stopRunning();}} 2021/9/2126暂停线程的执行等待条件满足再执行下面的例子显示线程的挂起和唤醒Applet第一次开始时,线程被启动浏览器改变页面时,小应用程序的stop()方法被调用,线程被挂起.浏览器回到原来的页面时,线程被唤醒. 2021/9/2127publicvoidstart(){if(mythread==null){mythread=newThread();mythread.start();}else{mythread.resume();}}publicvoidrun(){while(true){try{sleep(100);}catch(InterruptedExceptione){}}}publicvoidstop(){mythread.suspend();}. 2021/9/21285.Java多线程问题执行顺序多个线程运行时,调度策略为固定优先级调度.级别相同时,由操作系统按时间片来分配下面给出的例子中,共运行三个线程,它们做同样的事,每次打印循环次数和自己的序列号,运行结果表明,它们并不是连续运行的.如果给某个线程赋予较高的优先权,则发现这个进程垄断控制权thread.setPriority(Thread.MAX_PRIORITY) 2021/9/21297.3多线程问题//多个进程运行时执行顺序是交叉的publicclassMyThreadextendsThread{intthreadNum;publicstaticvoidmain(Stringargs[]){MyThreadarray[]=newMyThread[3];for(inti=0;i<3;i++)array[i]=newMyThread(i);for(inti=0;i<3;i++)array[i].start();}MyThread(intSerialNum){super();threadNum=SerialNum;}publicvoidrun(){for(intj=0;j<5;j++){System.out.println(threadNum+":<"+j+">");try{sleep(1000);}catch(InterruptedExceptione){};}System.out.println("thread"+threadNum+"bye.");}} 2021/9/2130如何写多线程1.分别定义不同的线程类,在各自的run方法中定义线程的工作classmythread1extendsThread{publicvoidrun{….}}classmythread2extendsThread{publicvoidrun{….}}2.在主类中实例化各线程类,并启动线程.publicclassdemoextendsApplet{publicvoidinit(){mythreadt1=newmythread1();mythreadt2=newmythread2();t1.start();t2.start();}} 2021/9/2131练习:将窗口分为上下两个区,分别运行两个线程,一个在上面的区域中显示由右向左游动的字符串,另一个在下面的区域从左向右游动的字符串.方法一:一个线程,在paint方法中使用两个输出字符串的语句publicvoidpaint(Graphicsg){ify1<0y1=200elsey1=y1-10;ify2>200y2=0elsey2=y2+10;g.drawString(“hello,Java!”,20,y1,);g.drawString(“hello,Java!”,40,y2,);} 2021/9/2132方法二:定义两个类,运行各自的线程,各自有自己的paint()方法.注意:两个Applet必须是panel类或者是canvas类,将Applet的区域分成两块,否则不能运行paint语句. 2021/9/2133importjavax.swing.*;importjava.awt.*;publicclassApplet1extendsJApplet{Ct1,t2;myCanvasc1,c2;ContainercontentPane=getContentPane();publicvoidinit(){c1=newmyCanvas();c2=newmyCanvas();contentPane.setLayout(newGridLayout(2,1));contentPane.validate();contentPane.add(c1);contentPane.add(c2);t1=newC(c1,5);t2=newC(c2,-5);t1.start();t2.start();}}classmyCanvasextendsCanvas{publicvoidpaint(Graphicsg,intx,inty){g.drawString("HelloWorld",x,y);}}classCextendsThread{myCanvasa;intsteps;intx;C(myCanvasb,intsize){a=b;steps=size;x=0;}publicvoidrun(){while(true){x=x+steps;if(x<0)x=a.getWidth();if(x>a.getWidth())x=0;a.repaint();a.paint(a.getGraphics(),x,50);try{sleep(10);}catch(InterruptedExceptione){}}}} 2021/9/2134线程间的通信1.线程间的通信可以用管道流,.创建管道流:PipedInputStreampis=newPipedInputStream();PipedOutputStreampos=newPipedOutputStream(pis);或:PipedOutputStreampos=newPipedOutputStream();PipedInputStreampis=newPipedInputStream(pos);线程1PipedOutputStreamPipedInputStream输出流outStream输入流inStream线程2 2021/9/2135管道流不能直接读写PrintStreamp=newPrintStream(pos);p.println(“hello”);DataInputStreamd=newDataInputStream(pis);d.readLine();2.通过一个中间类来传递信息.线程2线程1中间类mssm.write(s)s=m.read()write()read()printStreamDataInputStream 2021/9/2136管道流可以连接两个线程间的通信两个线程在运行,一个往外输出信息,一个读入信息.将一个写线程的输出通过管道流定义为读线程的输入.outStream=newPipedOutputStream();inStream=newPipedInputStream(outStream);newWriter(outStream).start();newReader(inStream).start(); 2021/9/2137主类Pipethread辅类Writer线程类辅类Reader线程类管道流将数据写到输出流从流中读数据输入流作为参数传给WriterWriter(outStream) 2021/9/21387.4多线程问题--线程间的通信.importjava.io.*;publicclassPipethread{publicstaticvoidmain(Stringargs[]){PipethreadthisPipe=newPipethread();thisPipe.process();}publicvoidprocess(){PipedInputStreaminStream;PipedOutputStreamoutStream;PrintStreamprintOut;try{outStream=newPipedOutputStream();inStream=newPipedInputStream(outStream);newWriter(outStream).start()newReader(inStream).start();}catch(IOExceptione){}}} 2021/9/21397.4多线程问题---线程间的通信classReaderextendsThread{privatePipedInputStreaminStream;publicReader(PipedInputStreami){inStream=i;}publicvoidrun(){Stringline;DataInputStreamd;booleanreading=true;d=newDataInputStream(inStream);while(reading&&d!=null){try{line=d.readLine();if(line!=null){System.out.println("Read:"+line);}elsereading=false;}catch(IOExceptione){};}try{Thread.sleep(4000);}catch(InterruptedExceptione){};}} 2021/9/21407.4多线程问题--线程间的通信.classWriterextendsThread{privatePipedOutputStreamoutStream;privateStringmessages[]={"Monday","Tuesday","Wednsday","Thursday","Friday:","Saturday:","Sunday:"};publicWriter(PipedOutputStreamo){outStream=o;}publicvoidrun(){PrintStreamp=newPrintStream(outStream);for(inti=0;i

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
关闭