多线程:并发
package com.wuming.demo01;
//多個(gè)線程同時(shí)操作同一個(gè)對(duì)象
//買火車票例子
//多個(gè)線程操作下不安全,出現(xiàn)紊亂
public class TestThread4 implements Runnable{/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see Thread#run()*///票數(shù)private int ticketNums=10;@Overridepublic void run() {while(true){if (ticketNums<=0){break;}//模擬延時(shí)try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"票");}}public static void main(String[] args) {TestThread4 ticket = new TestThread4();new Thread(ticket,"小明").start();new Thread(ticket,"老師").start();new Thread(ticket,"黃牛黨").start();}
}
老師-->拿到了第10票
黃牛黨-->拿到了第9票
小明-->拿到了第8票
小明-->拿到了第6票
老師-->拿到了第5票
黃牛黨-->拿到了第7票
小明-->拿到了第4票
老師-->拿到了第3票
黃牛黨-->拿到了第2票
黃牛黨-->拿到了第1票
老師-->拿到了第0票
小明-->拿到了第-1票
總結(jié)
- 上一篇: Python 递归函数 - Python
- 下一篇: C语言 main 函数 - C语言零基础