java多线程之引入Runnable

来源:互联网 发布:圣火名尊盾牌进阶数据 编辑:程序博客网 时间:2024/05/17 11:58

转载请注明出处

http://blog.csdn.net/pony_maggie/article/details/42402657


作者:小马


本节用一种新的方式重新实现Counter示例,介绍Runnable的使用。


Runnable是一个接口,我们的类只要继承这个接口并实现它的run方法即可实现多线程机制。如下所示:

public class Counter3 extends JApplet implements Runnable{private int count = 0;private boolean runFlag = true;private Thread selfThread = null;private JButton startButton = new JButton("Start");private JButton onoffButton = new JButton("Toggle");private JTextField t = new JTextField(10);public void run(){while(true){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO: handle exceptionSystem.err.println("Interrupted");}if(runFlag){t.setText(Integer.toString(count++));}}}

但是这里有一个问题,runnable没有start接口,如果启动呢? 还得借助于Thread类,它有一个带Runnable类型参数的构造函数:


java.lang.Thread.Thread(Runnable target)

可以这样用:

class StartL implements ActionListener{//点击start按钮触发go函数执行。public void actionPerformed(ActionEvent e){if(selfThread == null){selfThread = new Thread(Counter3.this);selfThread.start();}}}

这是在start按钮被点击时,生成一个Thread对象,以runnable实例作为参数。


其它部分的代码跟前面的示例都是一样的,不再列举。


那么问题来了,什么时候用Thread方式(counter2.java),什么时候又该用runnable方式呢? 在实际开发中一个多线程的操作很少使用Thread类,而是通过Runnable接口完成,主要是因为runnable更灵活一些。首先一个类只能继承一个父类,想像一下你的一个类如果继承Thread类实现多线程,就不能再继承其它类了,是不是很坑呢?


另外,Thread不利于实现资源共享,举个例子,卖票程序,有10张票,打算用三个线程卖,用Thread实现如下:

class MyThread extends Thread{  private int ticket=10;  public void run(){  for(int i=0;i<20;i++){  if(this.ticket>0){  System.out.println("卖票:ticket"+this.ticket--);  }  }  }  }public class ThreadTicket {  public static void main(String[] args) {  MyThread mt1=new MyThread();  MyThread mt2=new MyThread();  MyThread mt3=new MyThread();  mt1.start(); mt2.start();mt3.start();}  } 

会发现,每个线程都各卖了10张,共卖了30张票,但实际只有10张票,每个线程都卖自己的票,没有达到资源共享。如果用runnable实现就不一样了,如下:

class MyThread implements Runnable{  private int ticket=10;  public void run(){  for(int i=0;i<20;i++){  if(this.ticket>0){  System.out.println("卖票:ticket"+this.ticket--);  }  }  }  }   public class RunnableTicket {  public static void main(String[] args) {  MyThread mt=new MyThread();  new Thread(mt).start();  new Thread(mt).start(); new Thread(mt).start();  }  }; 


虽然开了三个线程,但是用的同一个对象实例化的,可以资源共享。


最后说一点,其实Thread类也是实现的runnable的接口,只要是线程都必须实现runnable接口。

1 0
原创粉丝点击