public class Test1Thread extends Thread {
private int ticketscount = 100;
@Override
public void run() {
while (true) {
sale();
}
}
private synchronized void sale(){
if (ticketscount > 0) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
int curent = ticketscount--;
System.out.println(String.format("%s卖出了第%s张票",
Thread.currentThread().getName(), curent));
}
}
}
public class TestRunable implements Runnable {
private int ticketscount = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true){
sale();
}
}
private void sale(){
try {
lock.lock();
if(ticketscount>0){
Thread.sleep(1000);
System.out.println(String.format("%s卖出了第%s张票",
Thread.currentThread().getName(),ticketscount--));
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class TestMain {
/**
* 对于java程序,只要有一个前台线程在运行,这个进程就不会结束
* 如果只有后台线程运行,进程会结束
*/
public static void test1(){
Test1Thread test1Thread = new Test1Thread();
Thread thread1 = new Thread(test1Thread);
thread1.setName("John");
thread1.setDaemon(false);
thread1.start();
Thread thread2 = new Thread(test1Thread);
thread2.setDaemon(false);
thread2.setName("BOB");
thread2.start();
}
public static void test2(){
TestRunable runable = new TestRunable();
new Thread(runable).start();
new Thread(runable).start();
}
public static void main(String[] args){
test2();
}
}