在java中,多线程的实习现有二种方式,一种是实现Runnable接口,另一种是继承Thread类
package thread; class MyThread extends Thread{ private String name; public MyThread(String name) { super(); this.name = name; } public void run(){ for(int i=0;i<10;i++){ System.out.println("线程开始:"+this.name+",i="+i); try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Test { public static void main(String[] args) { MyThread mt1=new MyThread("线程a"); MyThread mt2=new MyThread("线程b"); mt1.start(); mt2.start(); } }
package thread; import static java.lang.Thread.sleep; class MyThread implements Runnable{ private String name; public MyThread(String name) { this.name = name; } public void run(){ for(int i=0;i<10;i++){ System.out.println("线程开始:"+this.name+",i="+i); try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }; public class Test { public static void main(String[] args) { MyThread mt1=new MyThread("线程a"); MyThread mt2=new MyThread("线程b"); new Thread(mt1).start(); new Thread(mt2).start(); } }
以卖票程序为例,通过Thread类完成:
package 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 Test { public static void main(String[] args) { MyThread mt1=new MyThread(); MyThread mt2=new MyThread(); MyThread mt3=new MyThread(); mt1.start();//每个线程都各卖了10张,共卖了30张票 mt2.start();//但实际只有10张票,每个线程都卖自己的票 mt3.start();//没有达到资源共享 } } 每个线程都是自己单独的10张票,并没有共享资源
如果用Runnable就可以实现资源共享,下面看例子:
package thread; 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 Test { public static void main(String[] args) { MyThread mt=new MyThread(); new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一 new Thread(mt).start();//个实例化对象mt,就会出现异常 new Thread(mt).start(); } }
虽然现在程序中有三个线程,但是一共卖了10张票,也就是说使用Runnable实现多线程可以达到资源共享目的。
三 参考链接
点击打开链接