JavaPL 08 java thread & concurrent package

上传人:da****ge 文档编号:243097973 上传时间:2024-09-15 格式:PPT 页数:62 大小:499.50KB
返回 下载 相关 举报
JavaPL 08 java thread & concurrent package_第1页
第1页 / 共62页
JavaPL 08 java thread & concurrent package_第2页
第2页 / 共62页
JavaPL 08 java thread & concurrent package_第3页
第3页 / 共62页
点击查看更多>>
资源描述
,单击此处编辑母版标题样式,单击此处编辑母版文本样式,第二级,第三级,第四级,第五级,*,*,*,单击此处编辑母版标题样式,单击此处编辑母版文本样式,第二级,第三级,第四级,第五级,*,*,*,单击此处编辑母版标题样式,单击此处编辑母版文本样式,第二级,第三级,第四级,第五级,*,*,*,Java Programming Language,Java,语言程序设计,2011SCSTJPL08-6.0.0,JAVA,语言程序设计,第八讲,线程编程,第八讲 线程,概述,线程的创建,两种方式,线程的同步,synchronized,wait()/,notifyAll,()/notify(),线程的生命周期,3,概述,进程,(Process),程序,(Program),的一次,动态执行过程,占用特定的地址空间,在,某种程度,上相互隔离的、独立运行的程序,进程间通信,管道、消息、共享内存、,Socket,多任务,(Multitasking),操作系统,将,CPU,时间动态地划分给每个进程,操作系统同时执行多个进程,每个进程独立运行,进程的查看,Windows,系统,:,Ctrl+Alt+Del,Unix,系统,:,ps,or top,4,概述,5,概述,6,进程状态迁移,PCB,运行,就绪,阻塞,7,概述,线程,(Thread),线程是,进程中,一个“单一的连续控制流程”,(a single sequential flow of control)/,执行路径,一个进程可拥有,多个并行,的,(concurrent),线程,一个进程中的线程共享相同的内存单元,/,内存地址空间,可以访问相同的变量和对象,而且它们从同一堆,(heap),中分配对象,通信、数据交换、同步操作,轻量级进程,(lightweight process),实现代价小,管理容易,8,进程、线程关系,寄存器,进程,1,存储器,动态堆,静态数据,程序代码,堆栈,寄存器,进程,存储器,动态堆,静态数据,程序代码,堆栈,线程,1,寄存器,堆栈,线程,1,寄存器,进程,2,存储器,动态堆,静态数据,程序代码,堆栈,9,概述,Java,语言中的线程,第一个,在语言本身中显性地包含线程的,主流编程语言,,它没有把线程化看作是底层操作系统的工具,大多数现代的操作系统都支持线程,每个,Java,程序都至少有一个线程,主线程,当一个,Java,程序启动时,,JVM,会创建主线程,并在该线程中调用程序的,main(),方法,JVM,还创建了其它线程,如垃圾收集,(garbage collection),10,线程状态迁移,Created,Runnable,Blocked,Dead,new Thread(),start(),yield(),stop(),或,run()exit,stop(),sleep(),suspend(),wait() I/O,stop(),go,isAlive,11,概述,多线程,(,MultiThreading,),语言,java.lang.Thread,类,java.lang.Runnable,接口,为什么使用,? (,用途,),从提高程序执行效率的考虑,最大限度地利用,CPU,效率,应用在多处理器系统,(SMP-Symmetric,MultiProcessing,),执行异步或后台处理等,Client/Server,设计中的服务器端,如每个用户请求建立一个线程,实现多个请求同时并发,图形用户界面,(GUI),的设计中提高事件响应的灵敏度,12,概述,不宜使用多线程的场合,线程,不是万金油,占用资源角度,每个线程的调用栈,:Java,调用方法和局部变量栈,;,本机代码栈,(,一般是,C,语言,),时间开销角度,线程上下文切换开销,启动、终止和销毁,Thread,对象的开销,13,第八讲 线程,概述,线程的创建,两种方式,线程的同步,synchronized,wait()/,notifyAll,()/notify(),线程的生命周期,14,线程创建的两种方式,“,Subclassing,Thread and Overriding run”,继承,java.lang.Thread,类,重写,run(),方法,public class,MyThread,extends Thread, ,“Implementing the,Runnable,Interface”,实现,java.lang.Runnable,接口,Runnable,接口的唯一方法,public void run(),public class,MyClass,implements,Runnable, ,线程的创建,15,继承,Thread,实现线程,public class,SimpleThread,extends Thread,public,SimpleThread(String,str,) ,super(str,);,public void,run(),for (,int,i = 0; i 8; i+) ,System.out.println(i,+ +,getName,();,try ,sleep,(long)(Math.random,() * 1000);, catch (,InterruptedException,e) ,System.out.println(DONE,! +,getName,();,概述,public class,TwoThreadsDemo,public static void main (String,args,) ,new,SimpleThread(Jamaica).,start,(),;,new,SimpleThread(Fiji).,start,(),;,java.lang.Thread,public static void,sleep(long,millis,) throws,InterruptedException,Causes the currently executing thread to sleep,(temporarily cease execution) for the specified number of milliseconds.,main,Fiji,Jamaica,运行结果,:,0 Jamaica,0 Fiji,1 Jamaica,1 Fiji,2 Jamaica,2 Fiji,3 Jamaica,4 Jamaica,5 Jamaica,3 Fiji,6 Jamaica,7 Jamaica,4 Fiji,DONE! Jamaica,5 Fiji,6 Fiji,7 Fiji,DONE! Fiji,16,使用,Thread,方法,Thread.currentThread,(),start(),和,isAlive,(),public native synchronized void start() throws,IllegalThreadStateException,public final native,boolean,isAlive,(),getName()/setName,(),JVM,自动启动的线程如,main,Finalizer,AWT-EventQueue-0,等不要重命名,在,start(),调用前在,Thread,对象上调用,setName,(),启动后不要对其命名,给每个线程起一个简短、有意义的名字,每个线程名字不要相同,17,实现,Runnable,创建线程,线程的创建,public class,TwoThreadsDemo,public static void main (String,args,) ,new,SimpleThread1(Jamaica).,start(),;,new,SimpleThread1(Fiji).,start(),;,public class SimpleThread2,implements,Runnable,String name;,public SimpleThread2 (String,str,), name =,str,; ,public void,run(),for (,int,i = 0; i 8; i+) ,System.out.println(i,+ +name);,try ,Thread.sleep,(long)(Math.random,()*1000);, catch (,InterruptedException,e) ,System.out.println(DONE!+name,);,public class SimpleThread1,extends Thread,public SimpleThread1(String,str,) ,super(str,);,public void,run(),for (,int,i = 0; i 0 ),Thread.currentThread().interrupt,();,long,startTime,=,System.currentTimeMillis,();,try ,Thread.sleep,(2000);,System.out.println(“was,NOT interrupted”);, catch (,InterruptedException,e) ,System.out.println(“was,interrupt”);,System.out.println(“elapsedTime,= “,+ (,System.currentTimeMillis,() ,startTime,) );,java,PendingInterrupt,结果?,java,PendingInterrupt,yes,结果?,21,判断当前状态,isInterrupted,(),public,boolean,isInterrupted,(),不改变当前状态,如果线程被中断返回,true,Thread.interrupted,(),public,static,boolean,interrupted(),检查当前中断状态,并隐式重置为,false,是静态方法,只能报告调用它的线程中断状态,第二次调用总是返回,false. (,除非中断了线程,),22,中断设置判断,public class,TestInterruptState,public static void,main(String,args,) ,Thread t =,Thread.currentThread,();,System.out.println(“Point,A:,t.isInterrupted,() = “ +,t.isInterrupted,();,t.interrupt,();,System.out.println(“Point,B:,t.isInterrupted,() = “+,t.isInterrupted,();,System.out.println(“Point,C:,t.isInterrupted,() = “+,t.isInterrupted,();,try Thread.sleep(2000);,System.out.println(“was,NOT interrupted”);, catch(,InterruptedException,x),System.out.println(“was,interrupted”);,System.out.println(“Point,D:,t.isInterrupted,() = “+,t.isInterrupted,();,23,中断设置判断,public class TestInterruptState2 ,public static void,main(String,args,) ,System.out.println(“Point,X:,Thread.interrupted,() = “,+,Thread.interrupted,();,Thread.currentThread().interrupt,();,System.out.println(“Point,Y:,Thread.interrupted,() = “,+,Thread.interrupted,();,System.out.println(“Point,Z:,Thread.interrupted,() = “,+,Thread.interrupted,();,24,使用,InterruptedException,在调用,Thread.sleep,(),方法时,当被中断时可以友好终止休眠,并抛出一个,InterruptedException,异常,另外,Ojbect,中,wait(),方法的行为与,sleep(),类似,.,可以使用此抛出异常的模式设计自定义的方法的扩展。,如:一个计算偶尔的检查中断状态,如果被中断就停止计算。,25,使用,InterruptedException,public class,PiInterrupt,implements,Runnable,private double,latestPiEstimate,;,public void,run(),try ,System.out.println(“for,comparison,Math.PI,=“ +,Math.PI,);,calcPi(0.000000001);,System.out.println(“within,accurary, latest pi=“ +,latestPiEstimate,);, catch(,InterruptedException,x),System.out.println(“INTERRUPTED,! latest pi=“ +,latestPiEstimate,);,private void,calcPi(double,accurary,),throws,InterruptedException,latestPiEstimate,= 0.0;,long iteration = 0;,int,sign = -1;,while (,Math.abs(latestPiEstimate,Math.PI,) ,accurary,) ,if (,Thread.interrupted,() ),throw new,InterruptedException,();,iteration+; / pi = 4/1 4/3 + 4/5 4/7 + 4/9 - 4/11 ,sign = -sign;,latestPiEstimate,+= sign * 4.0 / ( 2 * iteration ) 1 );,public class Test,public static void main (String,args,) ,PiInterrupt,pi = new,PiInterrupt,();,Thread,t = new,Thread(,pi,);,t.,start,(),;,try ,Thread.sleep(10000);,t.interrupt,(),;,catch(InterruptedException,x) ,26,挂起和恢复线程,使用淘汰的方法,suspend(),和,resume(),27,使用,InterruptedException,public class,VisualSuspendResume,extends,JPanel,implements,Runnable,private static final String,symbolList,= “|”, “/”, “-”, “” ;,private Thread,runThread,;,private,JTextField,symbolTF,;,public,VisualSuspendResume,(),symbolTF,= new,JTextField,();,symbolTF.setEditable(false,);,symbolTF.setFont(new,Font(Monospaced,Font.BOLD, 26);,final,JButton,suspendB,= new,JButton(Suspend,);,final,JButton,resumeB,= new,JButton(Resume,);,suspendB.addActionListener(new,ActionListener,(),public void,actionPerformed(ActionEvent,e),suspendNow,();,);,resumeB.addActionListener(new,ActionListener,(),public void,actionPerformed(ActionEvent,e),resumeNow,();,);,JPanel,innerStackP,= new,JPanel,();,innerStackP.setLayout(new,GridLayout(0, 1, 3, 3);,innerStackP.add(symbolTF,);,innerStackP.add(suspendB,);,innerStackP.add(resumeB,);,this.setLayout(new,FlowLayout(FlowLayout.CENTER,);,this.add(innerStackP,);,28,使用,InterruptedException,private void,suspendNow,(),if (,runThread,!= null) / avoid,NullPointerException,runThread.suspend,();,private void,resumeNow,(),if (,runThread,!= null) / avoid,NullPointerException,runThread.resume,();,public void run() ,try ,runThread,=,Thread.currentThread,();,int,count = 0;,while(true,),symbolTF.setText,(,symbolList, count %,symbolList.length,);,Thread.sleep(200);,count+;,catch (,InterruptedException,x),finally ,/ thread dead,runThread,= null;,29,使用,InterruptedException,public static void,main(String,args,) ,VisualSuspendResume,vsr,= new,VisualSuspendResume,();,Thread t = new,Thread(vsr,);,t.start,();,JFrame,f = new,JFrame(Visual,Suspend Resume);,f.setContentPane(vsr,);,f.setSize(320, 200);,f.addWindowListener(new,WindowAdapter,(),public void,windowClosing(WindowEvent,e),System.exit(0);,);,f.setVisible(true,);, / end class,30,使用更好的机制,强制挂起容易导致问题,(,数据不一致或死锁,),通过设定一个指示标志,程序运行中查看这个标志来决定采取动作。,31,计时器,32,计时器,public class,SecondCounter,extends,JComponent,implements,Runnable,private,volatile,boolean,keepRunning,;,private Font,paintFont,;,private,volatile,String,timeMsg,;,private,volatile,int,arcLen,;,public,SecondCounter,() ,paintFont,= new,Font(SansSerif,Font.BOLD,14);,timeMsg,= never started;,arcLen,= 0;,33,计时器,public void,runClock,(),int,counter = 0;,keepRunning,= true;,while (,keepRunning,) ,try ,Thread.sleep(normalSleepTime,);, catch (,InterruptedException,e) ,counter+;,double,counterSecs,= counter / 10.0;,timeMsg,=,fmt.format(counterSecs,);,arcLen,= (,int)counterSecs,) % 60 ) * 360 / 60;,repaint();,public void,stopClock,() ,keepRunning,= false;,34,计时器,public void,paint,(Graphics,g),g.setColor(Color.BLACK,);,g.setFont(paintFont,);,g.drawString(timeMsg, 0, 15);,g.,fillOval,(0, 20, 100, 100); / black border,g.setColor(Color.WHITE,);,g.,fillOval,(3, 23, 94, 94); / non used with white,g.setColor(Color.BLUE,); / used part with blue,g.,fillArc,(2, 22, 96, 96, 90, -,arcLen,);,public void run() ,runClock,();,35,计时器,36,计时器,public class,SCRunnable,extends,JPanel,private,SecondCounter,sc;,private,JButton,startB,; private,JButton,stopB,;,public,SCRunnable,() ,sc = new,SecondCounter,();,startB,= new,JButton(start,);,stopB,= new,JButton(stop,);,stopB.setEnabled(false,);,startB.addActionListener(new,ActionListener,(),public void,actionPerformed(ActionEvent,evt,),startB.setEnabled(false,);,Thread,counterThread,= new,Thread(sc, ,SecondCounter,);,counterThread.start,();,stopB.setEnabled(true,);,stopB.requestFocus,();,);,37,守护线程,daemon thread,守护线程用于后台支持任务,在普通、非守护线程仍然运行时才需要。,当存在非守护线程存在时,,VM,不退出,当仅剩下守护线程时,,VM,将退出,设置:,public final void,setDaemon(boolean,on),38,第八讲 线程,概述,线程的创建,两种方式,线程的同步,synchronized,wait()/,notifyAll,()/notify(),线程的生命周期,39,独立执行,的,(independent)/,异步,的,(asynchronous),线程,共享资源的访问,多个线程,对,同一资源,进行操作,(,读,/,写,)-,协调,当多个线程访问同一数据项(如静态字段、可全局访问对象的实例字段或共享集合)时,需要确保它们协调了对数据的访问,这样它们都可以看到数据的一致视图,而且相互不会干扰另一方的更改,synchronized,关键词,wait() / notify() /,notifyAll,(),方法,等待,/,唤醒,线程的同步,40,不同步的例子,线程的同步,Producer,线程,Consumer,线程,CubbyHole,容器,每隔一定时间,放一个数,0,1,2,3,9,取数,一个程序,三个对象,41,线程的同步,public class,CubbyHole,private,int,contents;,public,int,get() return contents; ,public void,put(int,value), contents = value; ,public class Producer,extends Thread,private,CubbyHole,cubbyhole,;,public,Producer(CubbyHole,c), cubbyhole = c; ,public void,run(),for (,int,i = 0; i 10; i+) ,cubbyhole.put(i,);,System.out.println(Producer, + put: + i);,try ,sleep,(int)(,Math.random,(),* 100);, catch (,InterruptedException,e) ,public class Consumer,extends Thread,private,CubbyHole,cubbyhole,;,public,Consumer(CubbyHole,c), cubbyhole = c; ,public void,run(),int,value = 0;,for (,int,i = 0; i 10; i+) ,value =,cubbyhole.get,();,System.out.println(Consumer,“,+ got: + value);,public class Test ,public static void,main(String,args,) ,CubbyHole,h,= new,CubbyHole,();,Producer p = new,Producer(,h,);,Consumer c = new,Consumer(,h,);,p.start,();,c.start,();,42,线程的同步,多次重复取值,java Test,Producer put:0,Consumer got:0,Consumer got:0,Producer put:1,Consumer got:1,Consumer got:1,Producer put:2,Producer put:3,Producer put:4,Consumer got:4,Consumer got:4,Producer put:5,. . .,运行结果,漏取,43,如何同步,Producer,放一个数,,Consumer,取一个数,关键对象加锁,协调线程,线程的同步,Producer,线程,Consumer,线程,CubbyHole,容器,每隔一定时间,放一个数,0,1,2,3,9,取数,一个程序,三个对象,44,给关键部分,(Critical Section),加锁,(lock),CubbyHole,对象,synchronized,关键词,the two threads must,not simultaneously,access the,CubbyHole,.,The Java platform then associates,a lock,with,every object,that has synchronized code,线程的同步,public class,CubbyHole,private,int,contents;,public,int,get() return contents; ,public void,put(int,value) ,contents = value;,public class,CubbyHole,private,int,contents;,public,synchronized,int,get(), return contents; ,public,synchronized,void,put(int,value) ,contents = value;,45,线程的协调,the two threads must do some simple,coordination,.,Producer,通过某种方式告诉,Consumer,在,CubbyHole,中,有值,,而,Consumer,必须通过某种方式表示出,CubbyHole,中的值,已被取走,CubbyHole,对象,(Critical Section),线程的同步,java.lang.Object,public final void wait() throws,InterruptedException,public final void,wait(long,timeout) throws,InterruptedException,public final void,notifyAll,() /,唤醒所有等待的线程,public final void notify() /,随机唤醒一个等待的线程,46,线程的同步,public class,CubbyHole,private,int,contents;,private,boolean,available,= false;,public,synchronized,int,get() ,while (available = false) ,try ,wait();,/,打开锁,等候,Producer,填值, catch (,InterruptedException,e) ,available = false;,notifyAll,(),;,return contents;,public,synchronized,void,put(int,value) ,while (available = true) ,try ,wait();,/,打开锁,等候,Consumer,取值, catch (,InterruptedException,e) ,contents = value; available = true;,notifyAll,(),;,线程,consumer,get(),判断当前是否存有值,有,没有,设置为空,唤醒,producer,取值,释放锁定,等待新值,线程,producer,put(),判断当前是否存有值,有,没有,释放锁定,等待取值,放值,设置为有,唤醒,consumer,47,锁定和同步的几点说明,只能同步方法,不能同步变量或类,每个对象只有一个锁,不必同步类中所有的方法,可以有同步和非同步方法,如果两个线程要执行一个类中的,synchronized,方法,并且是同一个实例,则一次只能有一个线程执行方法,如果类有同步和非同步方法,则可以访问非同步方法。同步影响性能,使用不当会死锁。,线程进入睡眠,保持所有的锁。,线程可以获得多个锁。,可以同步代码块,而不是方法。,48,锁定和同步的几点说明,静态方法也可以同步,但要了解其意义,public static synchronized,int,getCount,() ,return count;,等价于,public static,int,getCount,() ,synchronized(,MyClass.class,) ,return count ;,Class,cl,=,Class.forName(“MyClass,”);,synchronized(cl,) . ,49,锁定和同步的几点说明,非静态方法彼此阻塞,静态方法彼此阻塞,静态与非静态之间永远不彼此阻塞,同步块看在什么对象上阻塞,50,线程的交互,注意一点:,wait() notify(),notifyAll,(),必须在同步环境中才能调用, 线程只用拥有对象上的锁才能调用这些方法。,notify,通知一个线程,,notifyAll,通知所有线程,51,第八讲 线程,概述,线程的创建,两种方式,线程的同步,synchronized,wait()/,notifyAll,()/notify(),线程的生命周期,52,线程启动,class SimpleThread1,extends Thread, ,new,SimpleThread1(Jamaica).,start(),;,class SimpleThread2,implements,Runnable, ,SimpleThread2 a = new SimpleThread2(Jamaica);,Thread,thread,= new,Thread(a,);,thread.start,();,线程启动后执行,run(),方法,该方法运行结束,则线程停止,A thread dies naturally when the,run method exits,线程的生命周期,public void run() ,int,i = 0;,while (i 0 ? (String) names.remove(0) : null ;,public static void,main(String,args,) ,final,NameList,nl,= new,NameList,();,nl.add(“my,god “);,class,NameDropper,extends Thread ,public void run() ,System.out.println,(,nl.removeFirst,() ); ,new,NameDropper().start,(); / t1,new,NameDropper().start,(); / t2,56,Quiz 1,public class,Letters,extends,Thread ,private,String name;,public,Letters(String,name) ,this,.name,= name; ,public void,write() ,System.out.print(name,);,System.out.print(name,);,public static void,main(String,.,args,),new,Letters(“X”).start,();,new,Letters(“Y”).start,();,We want to guarantee that the output can be either XXYY or YYXX, but never XYXY or any other combination. Which of the following method definitions could be added to the Letters class to make this guarantee ? ( Choose all that apply ),A public void run() write();,B public synchronized void run() write();,C public static synchronized void run() write();,D public void run() ,synchronized(Letters.class,) write(); ,E public void run() ,synchronized(System.out,) write(); ,F public void run() ,synchronized(System.out.class,) write(); ,G public void run() ,synchronized(this,) write(); ,57,Quiz 2,class,MyThread,extends,Thread ,public static void,main(String,.,args,),MyThread,t =,new,MyThread,();,Thread x =,new,Thread(t,);,x.start,();,public void,run() ,for,(,int,i = 0; i 3; +i ) ,System.out.print(i,+ “.” );,What is the result ?,A,Compilation fails,B,1.2.3.,C,0.1.2.3.,D 0.1.2.,E,An exception occurs at runtime,58,Quiz 3,Which are methods of the Object class ? (choose all that apply ),A notify(),B,notifyAll,(),C,isInterrupted,(),D,synchronized(),E interrupt(),F,wait(long,msecs,),G,sleep(long,msecs,),H,yield(),59,Quiz 4,public class,ThreadDemo,synchronized void,a() ,actBusy,(); ,static synchronized void,b() ,actBusy,(); ,static void,actBusy,() ,try, Thread.sleep(1000);,catch,(InterruptedException,e) ,public static void,main(String,.,args,),final,ThreadDemo,x =,new,ThreadDemo,();,final,ThreadDemo,y =,new,ThreadDemo,();,Runnable,runnable,=,new,Runnable,() ,public void,run() ,int,option = (,int,) (,Math.random,() * 4);,switch,(option) ,case,0:,x.a,();,break,;,case,1:,x.b,();,break,;,case,2:,y.a,();,break,;,case,3:,y.b,();,break,;,;,Thread t1 =,new,Thread(runnable,);,Thread t2 =,new,Thread(runnable,);,t1.start();,t2.start();,60,Quiz 4,Which of the following pairs of methods invocations
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 图纸专区 > 小学资料


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!