网站大量收购独家精品文档,联系QQ:2885784924

[理学]chap8Java高级编程.ppt

  1. 1、本文档共38页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 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

文档评论(0)

ipbohn97 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档