Java使用Thread和Runnable的線程實現(xiàn)方法比較
本文實例講述了Java使用Thread和Runnable的線程實現(xiàn)方法。分享給大家供大家參考,具體如下:
一 使用Thread實現(xiàn)多線程模擬鐵路售票系統(tǒng)
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方法中產(chǎn)生4個線程
1 代碼
public class ThreadDemo
{
public static void main(String[]args)
{
// 啟動了四個線程,分別執(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 運行
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接口實現(xiàn)多線程,并實現(xiàn)資源共享
1 代碼
public class RunnableDemo
{
public static void main( String[] args )
{
TestThread newTh = new TestThread( );
// 啟動了四個線程,并實現(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 運行
Thread-0 出售票 5
Thread-0 出售票 4
Thread-0 出售票 3
Thread-0 出售票 2
Thread-0 出售票 1
更多java相關內(nèi)容感興趣的讀者可查看本站專題:《Java面向對象程序設計入門與進階教程》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
spring boot教程之產(chǎn)生的背景及其優(yōu)勢
這篇文章主要介紹了spring boot教程之產(chǎn)生的背景及其優(yōu)勢的相關資料,需要的朋友可以參考下2022-08-08
idea如何debug看springsecurity的過濾器順序
這篇文章主要介紹了idea如何debug看springsecurity的過濾器順序,文中通過圖文結合的方式給大家介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2024-04-04
springboot+spring?data?jpa實現(xiàn)新增及批量新增方式
這篇文章主要介紹了springboot+spring?data?jpa實現(xiàn)新增及批量新增方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

