介绍java多线程例子
Thread-2 is saling 1
Thread-3 is saling 0
Thread-0 is saling -1
Thread-1 is saling -2
卖出了0、-1和-2的票,证明上述这种写法是存在线程安全的。
线程同步
为了解决线程安全的问题,就要引入线程同步。
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;
String str = ""; //此时str为公共对象
public void run() {
while(true) {
synchronized(str) {
if(tickets<=0)
break;
//try{Thread.sleep(10);}catch(Exception e) {}
System.out.println(Thread.currentThread().getName() + " is saling " + tickets--);
}
}
}
}
在上面的代码中加入synchronized,就可以实现线程同步了。
运行结果 写道
hread-2 is saling 5
hread-3 is saling 4
hread-1 is saling 3