遇到的問題:
多線程生產者與消費者模型;尚未解決!
jar
---------------
jar cvf xxx.jar -C classes/ .
進程
-----------------
進程之間內存式隔離的。內存不共享。
線程
-----------------
程序執行過程中,併發執行的代碼段。
線程之間可以共享內存。
Thread : 線程類。
start()//通知cpu,可以開始執行該線程。
run()//線程具體執行的代碼段。
Thread t = new Thread();
t.start();
Thread.currentThread()//得到當前的執行線程。
yield()//讓線程放棄cpu的搶佔權。
sleep(int mils)//讓當前線程休眠指定的毫秒數.
線程安全:增加了同步處理。確保在同一時刻,只有一個線程執行同步代碼。
同步方法使用的當前對象作爲同步對象。
靜態方法可以加同步處理,使用Class作爲同步對象。
KTV :
Box ://3
Waiter//守護線程 daemon Thread.setDaemon(true);
yield()
join()
sleep(int ms);
setDaemon(true);//線程啓動前設置
isDaemon();//指定線程是否是守護線程
start();//啓動線程
run();//
notify()//選擇一個監控器對象等待隊列中的線程進行通知。
notifyAll()//選擇所有監控器對象等待隊列中的線程進行通知。
wait()//將當前線程放入監控器的等待隊列中。
wait(int n )//線程進入到等待隊列後,最多等待n長時間,時間一旦,自動喚醒。
例:5輛車依次通過山洞
public class ThreadDemo { public static void main(String[] args) throws Exception { Thread t1=new Thread(new MultiThreads(new Car("one"))); Thread t2=new Thread(new MultiThreads(new Car("two"))); Thread t3=new Thread(new MultiThreads(new Car("three"))); Thread t4=new Thread(new MultiThreads(new Car("four"))); Thread t5=new Thread(new MultiThreads(new Car("five"))); t1.start(); System.out.println("t2---"+t2.isAlive()); t1.join(); t2.start(); System.out.println("t1---t2"+t1.isAlive()+"--"+t2.isAlive()); t2.join(); t3.start(); t3.join(); t4.start(); t4.join(); t5.start(); t5.join(); } } class MultiThreads implements Runnable { private Car car; public MultiThreads(Car car) { super(); this.car = car; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public void run() { try { System.out.println(car.getName() + "-begin"); car.cross(); Thread.sleep(1000); System.out.println(car.getName() + "-end"); System.out.println(); } catch (InterruptedException e) { e.printStackTrace(); } } } class Car { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Car() { super(); } public Car(String name) { super(); this.name = name; } public void cross() { System.out.println(getName() + "----cross through----"); } }