Thread和Runnable线程实现比较

墨蓝 2021-09-29 12:40 452阅读 0赞

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

1 代码

  1. public class ThreadDemo
  2. {
  3. public static void main( String[] args )
  4. {
  5. TestThread newTh = new TestThread( );
  6. // 一个线程对象只能启动一次
  7. newTh.start( );
  8. newTh.start( );
  9. newTh.start( );
  10. newTh.start( );
  11. }
  12. }
  13. class TestThread extends Thread
  14. {
  15. private int tickets = 5;
  16. public void run( )
  17. {
  18. while( tickets > 0 )
  19. {
  20. System.out.println( Thread.currentThread().getName( ) + " 出售票 " + tickets );
  21. tickets -= 1;
  22. }
  23. }
  24. }

2 运行

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

3 说明

一个线程只能启动一次

二 main方法中产生4个线程

1 代码

  1. public class ThreadDemo
  2. {
  3. public static void main(String[]args)
  4. {
  5. // 启动了四个线程,分别执行各自的操作
  6. new TestThread( ).start( );
  7. new TestThread( ).start( );
  8. new TestThread( ).start( );
  9. new TestThread( ).start( );
  10. }
  11. }
  12. class TestThread extends Thread
  13. {
  14. private int tickets = 5;
  15. public void run( )
  16. {
  17. while (tickets > 0)
  18. {
  19. System.out.println(Thread.currentThread().getName() + " 出售票 " + tickets);
  20. tickets -= 1;
  21. }
  22. }
  23. }

2 运行

  1. Thread-0 出售票 5
  2. Thread-0 出售票 4
  3. Thread-0 出售票 3
  4. Thread-0 出售票 2
  5. Thread-0 出售票 1
  6. Thread-1 出售票 5
  7. Thread-1 出售票 4
  8. Thread-1 出售票 3
  9. Thread-1 出售票 2
  10. Thread-1 出售票 1
  11. Thread-2 出售票 5
  12. Thread-2 出售票 4
  13. Thread-2 出售票 3
  14. Thread-2 出售票 2
  15. Thread-2 出售票 1
  16. Thread-3 出售票 5
  17. Thread-3 出售票 4
  18. Thread-3 出售票 3
  19. Thread-3 出售票 2
  20. Thread-3 出售票 1

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

1 代码

  1. public class RunnableDemo
  2. {
  3. public static void main( String[] args )
  4. {
  5. TestThread newTh = new TestThread( );
  6. // 启动了四个线程,并实现了资源共享的目的
  7. new Thread( newTh ).start( );
  8. new Thread( newTh ).start( );
  9. new Thread( newTh ).start( );
  10. new Thread( newTh ).start( );
  11. }
  12. }
  13. class TestThread implements Runnable
  14. {
  15. private int tickets = 5;
  16. public void run( )
  17. {
  18. while( tickets > 0 )
  19. {
  20. System.out.println( Thread.currentThread().getName() + " 出售票 " + tickets );
  21. tickets -= 1;
  22. }
  23. }
  24. }

2 运行

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

发表评论

表情:
评论列表 (有 0 条评论,452人围观)

还没有评论,来说两句吧...

相关阅读

    相关 【多线】——Thread VS Runnable

    进程和线程的关系     多个线程构成一个进程,线程是进程中的一个元素,例如QQ.exe查看电脑进程的时候发现只有一个进程,但是我们可以同时和多个用户聊天交流,而且可以一