1、线程的状态有新建、就绪、运行、阻塞、死亡。
2、创建线程通过继承Thread类或实现Runable接口。
3、线程的start()方法作用是开启一个线程执行run方法,且start不允许重复调用,线程的run()方法,则是在当前主线程中调用线程的run方法,可以重复调用,如果直接调用run()方法,意味着会将run()当一个主方法进行执行,并不会在一个线程中进行执行。
4、Synchronized同步锁,给方法添加同步锁后,一次只允许一个线程进行访问,其他线程进入阻塞状态,等待前一个线程访问结束后方可访问。
5、notify()随机唤醒一个线程;notifyAll()唤醒所有的线程;wait()让当前线程处于阻塞状态,等待唤醒;wait(1000)等待1秒;join暂停当前线程等待调用的线程优先执行完成。
6、Semaphore进行限流,定义最大线程数量。
public class Acount {
private int money;
public Acount(int money) {
this.money = money;
}
public synchronized void getMoney(int money){
while (this.money < money || this.money == 0) {
System.out.println("取款:"+money+",当前余额Semaphore为:"+this.money+",余额不足,请等待:");
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.money = this.money - money;
System.out.println("取出:"+money+" 还剩余:"+this.money);
}
public synchronized void setMoney(int money) {
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
this.money = this.money + money;
notifyAll();
System.out.println("存入:"+money+" 还剩余:"+this.money);
}
/**
* @param args
*/
public static void main(String[] args) {
Acount acount = new Acount(0);
Blank blank = new Blank(acount);
Customer customer = new Customer(acount);
Thread thread1 = new Thread(blank);
Thread thread2 = new Thread(customer);
thread1.start();
thread2.start();
}
}
class Blank extends Thread{
Acount acount;
public Blank(Acount acount){
this.acount = acount;
}
public void run(){
while(true){
int money = (int)(Math.random() * 1000);
acount.setMoney(money);
}
}
}
class Customer extends Thread{
Acount acount;
public Customer(Acount acount){
this.acount = acount;
}
public void run(){
while(true) {
int money = (int)(Math.random() * 1000);
acount.getMoney(money);
}
}
}