买票
package thread;
public class ThreeUnsafeCases {
public static void main ( String[ ] args) {
BuyTicket buyTicket = new BuyTicket ( ) ;
new Thread ( buyTicket, "You" ) . start ( ) ;
new Thread ( buyTicket, "I" ) . start ( ) ;
new Thread ( buyTicket, "He" ) . start ( ) ;
}
}
class BuyTicket implements Runnable {
private int ticketNumber = 10 ;
@Override
public void run ( ) {
while ( true ) {
if ( ticketNumber <= 0 ) {
return ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + " get " + ticketNumber-- ) ;
}
}
}
银行取钱
package thread;
public class ThreeUnsafeCasesBank {
public static void main ( String[ ] args) {
Account account = new Account ( 100 , " savings " ) ;
Drawing You = new Drawing ( account, 50 , " You " ) ;
Drawing She = new Drawing ( account, 100 , " She " ) ;
You. start ( ) ;
She. start ( ) ;
}
}
class Account {
int money;
String name;
public Account ( int money, String name) {
this . money = money;
this . name = name;
}
}
class Drawing extends Thread {
Account account;
int drawingMoney;
int nowMoney;
public Drawing ( Account account, int drawingMoney, String name) {
super ( name) ;
this . account= account;
this . drawingMoney= drawingMoney;
}
@Override
public void run ( ) {
if ( account. money- drawingMoney< 0 ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "先生,您的余额不足。" ) ;
return ;
}
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
if ( Thread. currentThread ( ) . getName ( ) . equals ( " You " ) ) {
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
account. money = account. money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System. out. println ( account. name+ " balance is " + account. money) ;
System. out. println ( this . getName ( ) + " money is now " + nowMoney) ;
}
}
线程集合
package thread;
import java. util. ArrayList;
public class ArrayListThread {
public static void main ( String[ ] args) throws InterruptedException {
ArrayList< String> strings = new ArrayList < > ( ) ;
for ( int i = 0 ; i < 10000 ; i++ ) {
new Thread ( ( ) - > {
strings. add ( Thread. currentThread ( ) . getName ( ) ) ;
} ) . start ( ) ;
}
Thread. sleep ( 1000 ) ;
System. out. println ( strings. size ( ) ) ;
}
}
https://www.bilibili.com/video/BV1V4411p7EF?p=19