- 1、本文档共38页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
[理学]chap8Java高级编程
在程序中实现多线程 两个关键性操作: 定义用户线程的操作,即实现run方法 在适当的时候建立用户线程实例,即用户线程对象 创建Thread类的子类 用户要创建自己的Thread类的子类,并在子类中重定义run方法,这个方法中包含了用户线程想要的操作。这样用户程序需要建立自己的线程是,它只需要创建Thread类的子类的对象就可以了。 public class testthread{ public static void main(String args[]){ System.out.println(“this is main thread”); mythread mt1=new mythread(); mt1.start(); System.out.println(“also main thread”); try{Thread.sleep(500);}catch(Exception e){} } } class mythread extends Thread{ public void run() { int i=1; while(true){System.out.print(“mythread”+i);i++; try{ if (i100) sleep(500);}catch(Exception e){ }}} } 当一个类已经有一个父类就不能使用thread,因为java不支持多继承。 用户只要实现接口中的run方法即可。当用户程序需要创建新线程时,只要以这个实现了run方法的类为参数创建系统类Thread的对象,就可以把用户实现的run方法继承过来 实现Runnable接口 public class tthread extends Applet implements Runnable{ public void init(){Label l1=new Label(“线程1”);tf1; Label l2=new Label(“线程2”); tf2 ;add….;} public void start(){ Thread thread1=new Thread(this,”thread1”); Thread thread2=new Thread(this,”thread2”); thread1.start(); thread2.start();} public void run() {try{Thread.sleep(500);}catch(…){…} curentrun=Thread.currentThread().getName(); while(true){if(currentrun.equals(“thread1”)) {count1++; tf1.setText(“线程1”+count1);} if(currentrun.equals(“thread1”)) {count2++; tf2.setText(“线程2”+count2);}}} Interface Runnable All Known Implementing Classes: AsyncBoxView.ChildState, Reoducer, Thread, TimerTask public interface Runnable The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped. In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a
您可能关注的文档
最近下载
- 物理丨山东省实验中学2025届高三下学期3月第五次诊断考试物理试卷及答案.pdf VIP
- MOS集成电路工艺入门资料PPT课件.pptx
- 跨学科实践活动1 探究土壤酸碱性对植物生长的影响 课件(共22张PPT)2025年中考化学一轮考点研究(人教版).pptx VIP
- 线段图法解决和差问题--奥数专题(课件)-2021-2022学年数学三年级上册 全国通用.ppt
- 2025年安阳职业技术学院单招职业适应性测试题库学生专用.docx
- 2025届山东省实验中学高三第五次诊物理试题.pdf VIP
- 凉山州小学数学教师业务素质考试试题(真题+训练).pdf
- 【经济学课件】经济学原理曼昆.ppt VIP
- 幼儿园讲座培训课件:幼儿园保育教育质量评估指南.pptx
- 2025年安阳职业技术学院单招职业倾向性考试题库新版.docx
文档评论(0)