温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java使用Thread和Runnable的线程实现方法比较

发布时间:2020-10-04 10:09:06 来源:脚本之家 阅读:132 作者:cakincqm 栏目:编程语言

本文实例讲述了Java使用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

更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI