1.线程之间状态的转换(偷了张图,哈哈)
2.具体网址(写的很好很详细):https://blog.csdn.net/jiangwei0910410003/article/details/19962627
3.我自己的想法:创建线程时,继承Thread和实现Runable接口,线程都是随机的,但是实现Runable可以实现同一资源的共享。
package com.briup.chap10; public class SynchTest implements Runnable{ private Ticket ticket; //创建当前线程对象,一开始构建时就拥有买票功能 public SynchTest(Ticket ticket){ this.ticket=ticket; } public void run() { //如果票的数量大于0,可以调用sale进行卖票 while(ticket.getNum()>0){ synchronized (ticket) { ticket.sale(); System.out.println(Thread.currentThread().getName()+"余票:"+ticket.getNum()); // try { // Thread.sleep(10); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } } } public static void main(String[] args) { //一开始构建有100张票 Ticket ticket=new Ticket(10); //每个窗口都是这100张票 SynchTest st=new SynchTest(ticket); Thread t1=new Thread(st,"上海火车站"); Thread t2=new Thread(st,"太原火车站"); t1.start(); t2.start(); } } class Ticket{ private int num; public Ticket(){} public Ticket(int num){ this.num=num; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public void sale(){ num--; } }
运行结果:
上海火车站余票:9
上海火车站余票:8
太原火车站余票:7
上海火车站余票:6
上海火车站余票:5
上海火车站余票:4
上海火车站余票:3
上海火车站余票:2
上海火车站余票:1
上海火车站余票:0
太原火车站余票:-1
package com.briup.chap10;
public class SynchTest2 extends Thread{
private static int num=10;
@Override
public void run() {
print();
// synchronized (new Integer(num)) {}
}
public synchronized void print(){
while(num>0){
num--;
System.out.println(getName()+" num:"+num);
}
}
public static void main(String[] args) {
SynchTest2 st=new SynchTest2();
SynchTest2 st2=new SynchTest2();
st.setName("first");
st2.setName("second");
st.start();
st2.start();
}
}
运行结果:
second num:8
second num:7
second num:6
second num:5
second num:4
first num:8
first num:2
first num:1
first num:0
second num:3