介绍java多线程例子
另外,在运行加入了synchronized同步块的程序的时会发现速度明显比没有同步块的程序要慢的多,所以在确定不会出现线程安全问题的程序中不要加入同步块,就像我们经常先使用Vector还是有ArrayList呢?它们两个的功能基本是完全一样的都是List,而Vector中的函数考虑了线程同步,ArrayList没有,这下就非常明显了,如果需要保证线程安全是就用Vector,不需要就用ArrayList效率高些。
同步函数
同步函数实现
class ThreadDemo {
public static void main(String[] args) {
TestThread t = new TestThread();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TestThread implements Runnable {
int tickets = 100;
public void run() {
while(true) {
sale();
}
}
public synchronized void sale() {
if(tickets<=0)
return;
try{Thread.sleep(10);}catch(Exception e) {}
System.out.println(Thread.currentThread().getName() + " is saling " + tickets--);
}
}
同步函数实际上同步的是this对象,这样如果要想某一个同步块和一个同步函数同步,就在同步块中使用this对象。
Java 多线程例子7 线程安全 死锁
死锁:在多个线程里对多个同步对象具有循环依赖时常会出现死锁。最简单的死锁例子就是线程一得到了A对象的锁旗标想得到B对象的锁旗标,线程二得到了B对象的锁旗标想得到A对象的锁旗标,这样线程一和线程二就形成了死锁。