欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java使用Thread和Runnable的線程實(shí)現(xiàn)方法比較

 更新時(shí)間:2019年10月14日 11:48:20   作者:cakincqm  
這篇文章主要介紹了Java使用Thread和Runnable的線程實(shí)現(xiàn)方法,結(jié)合實(shí)例形式對(duì)比分析了Java使用Thread和Runnable實(shí)現(xiàn)與使用線程的相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Java使用Thread和Runnable的線程實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:

一 使用Thread實(shí)現(xiàn)多線程模擬鐵路售票系統(tǒng)

1 代碼

public class ThreadDemo
{
  public static void main( String[] args )
  {
    TestThread newTh = new TestThread( );
    // 一個(gè)線程對(duì)象只能啟動(dòng)一次
    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 運(yùn)行

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 說(shuō)明

一個(gè)線程只能啟動(dòng)一次

二 main方法中產(chǎn)生4個(gè)線程

1 代碼

public class ThreadDemo
{
  public static void main(String[]args)
  {
    // 啟動(dòng)了四個(gè)線程,分別執(zhí)行各自的操作
    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 運(yùn)行

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接口實(shí)現(xiàn)多線程,并實(shí)現(xiàn)資源共享

1 代碼

public class RunnableDemo
{
  public static void main( String[] args )
  {
    TestThread newTh = new TestThread( );
    // 啟動(dòng)了四個(gè)線程,并實(shí)現(xiàn)了資源共享的目的
    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 運(yùn)行

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

更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論