Thread和Runnable线程实现比较

一 使用Thread实现多线程模拟铁路售票系统

1 代码

public class ThreadDemo
{
    public static void main( String[] args )
    {
        TestThread newTh = new TestThread( );
        // 一个线程对象只能启动一次
        newTh.start( );
        newTh.start( );
        newTh.start( );
        newTh.start( );
    }
}
class TestThread extends Thread
{
    private int tickets = 5;
    public void run( )
    {
        while( tickets > 0 )
        {
            System.out.println( Thread.currentThread().getName( ) + " 出售票 " + tickets );
            tickets -= 1;
        }
    }
}

2 运行

Thread-0 出售票 5
Thread-0 出售票 4
Thread-0 出售票 3
Thread-0 出售票 2
Thread-0 出售票 1
Exception in thread "main" java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Thread.java:708)
    at ThreadDemo.main(ThreadDemo.java:16)

3 说明

一个线程只能启动一次

二 main方法中产生4个线程

1 代码

public class ThreadDemo
{
    public static void main(String[]args)
    {
        // 启动了四个线程,分别执行各自的操作
        new TestThread( ).start( );
        new TestThread( ).start( );
        new TestThread( ).start( );
        new TestThread( ).start( );
    }
}
class TestThread extends Thread
{
    private int tickets = 5;
    public void run( )
    {
        while (tickets > 0)
        {
            System.out.println(Thread.currentThread().getName() + " 出售票 " + tickets);
            tickets -= 1;
        }
    }
}

2 运行

Thread-0 出售票 5
Thread-0 出售票 4
Thread-0 出售票 3
Thread-0 出售票 2
Thread-0 出售票 1
Thread-1 出售票 5
Thread-1 出售票 4
Thread-1 出售票 3
Thread-1 出售票 2
Thread-1 出售票 1
Thread-2 出售票 5
Thread-2 出售票 4
Thread-2 出售票 3
Thread-2 出售票 2
Thread-2 出售票 1
Thread-3 出售票 5
Thread-3 出售票 4
Thread-3 出售票 3
Thread-3 出售票 2
Thread-3 出售票 1

三 使用Runnable接口实现多线程,并实现资源共享

1 代码

public class RunnableDemo
{
    public static void main( String[] args )
    {
        TestThread newTh = new TestThread( );
        // 启动了四个线程,并实现了资源共享的目的
        new Thread( newTh ).start( );
        new Thread( newTh ).start( );
        new Thread( newTh ).start( );
        new Thread( newTh ).start( );
    }
}
class TestThread implements Runnable
{
    private int tickets = 5;
    public void run( )
    {
        while( tickets > 0 )
        {
            System.out.println( Thread.currentThread().getName() + " 出售票 " + tickets );
            tickets -= 1;
        }
    }
}

2 运行

Thread-0 出售票 5
Thread-0 出售票 4
Thread-0 出售票 3
Thread-0 出售票 2
Thread-0 出售票 1

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值