Java 多线程 Runable 接口

来源:互联网 发布:大数据时代 mobi 编辑:程序博客网 时间:2024/05/07 00:31

采用Thread方法: 意义:启动3个线程,开始卖票,总共有10张票

第一种方法:采用Thread 方法

class MyThreadDemo 
{
public static void main(String[] args) 
{
 
        Mythread mt1 = new Mythread();
Mythread mt2 = new Mythread();
Mythread mt3 = new Mythread();


mt1.start();
mt2.start();
mt3.start();





}
}

运行结果:

---------- java运行 ----------
剩余的票数:10
剩余的票数:9
剩余的票数:8
剩余的票数:10
剩余的票数:9
剩余的票数:8
剩余的票数:7
剩余的票数:6
剩余的票数:5
剩余的票数:4
剩余的票数:3
剩余的票数:2
剩余的票数:1
剩余的票数:10
剩余的票数:9
剩余的票数:7
剩余的票数:8
剩余的票数:7
剩余的票数:6
剩余的票数:5
剩余的票数:4
剩余的票数:3
剩余的票数:6
剩余的票数:2
剩余的票数:1
剩余的票数:5
剩余的票数:4
剩余的票数:3
剩余的票数:2
剩余的票数:1


输出完成 (耗时 0 秒) - 正常终止


结论:使用Thread 方法 资源没有共享,是错误的!


使用Runnable方法

class Mythread extends Thread
{
private int  ticket = 10;
    
public void run()
{
for(int i=0; i<100; i++)
if(ticket>0)
System.out.println("剩余的票数:"+ticket--);
}
}





class MyRunnableDemo 

{
public static void main(String[] args) 
{
 
       MyRunnable  mr = new MyRunnable();


  new Thread(mr).run();
  new Thread(mr).run();
  new Thread(mr).run();


}
}


class MyRunnable implements Runnable
{
private int  ticket = 10;
    
public void run()
{
for(int i=0; i<100; i++)
if(ticket>0)
System.out.println("剩余的票数:"+ticket--);
}


}


运行结果:

-------- java运行 ----------
剩余的票数:10
剩余的票数:9
剩余的票数:8
剩余的票数:7
剩余的票数:6
剩余的票数:5
剩余的票数:4
剩余的票数:3
剩余的票数:2
剩余的票数:1


输出完成 (耗时 0 秒) - 正常终止


结论:资源共享了。保证了程序的健壮性

            避免单继承带来的影响。

            适合多线程对同一个资源的操作。



1)多线程采用继承Thread类和实现Runnable接口。无论采用何种方法,都要复写run()方法。

2)采用Thread方法与实现Runnable方法相比,会有单继承的局限

3)Thread类是Runnbale接口的子类。无论采用何种方法,都要采用靠Thread 的start()方法实现

4)Runnable还实现了数据共享的作用。