没有同步的情况
class MyThread1 implements Runnable
{
private int ticket=5;
@Override
public void run() {
for(int x =0;x<20;x++)
{
if(ticket>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票:"+this.ticket--);
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread1 mt = new MyThread1();
new Thread(mt,"票贩子A").start();
new Thread(mt,"票贩子B").start();
new Thread(mt,"票贩子C").start();
new Thread(mt,"票贩子D").start();
}
}
票贩子C卖票:5
票贩子D卖票:5
票贩子B卖票:4
票贩子A卖票:3
票贩子D卖票:2
票贩子C卖票:1
票贩子A卖票:-1
票贩子B卖票:0
票贩子D卖票:-2
可以看到又相同的票被卖了,还出现了复数票的情况。
实现同步的关键字synchronized,可以通过两种方式使用
使用同步代码块实现同步
class MyThread1 implements Runnable
{
private int ticket=10;
@Override
public void run() {
for(int x =0;x<20;x++)
{
synchronized(this){
if(ticket>0) {
System.out.println(Thread.currentThread().getName()+"卖票:"+this.ticket--);
}
}
}
}
}
public class SynchronizedThread {
public static void main(String[] args) {
MyThread1 mt = new MyThread1();
new Thread(mt,"票贩子A").start();
new Thread(mt,"票贩子B").start();
new Thread(mt,"票贩子C").start();
new Thread(mt,"票贩子D").start();
}
}
票贩子A卖票:10
票贩子D卖票:9
票贩子C卖票:8
票贩子B卖票:7
票贩子C卖票:6
票贩子C卖票:5
票贩子C卖票:4
票贩子D卖票:3
票贩子A卖票:2
票贩子D卖票:1
调用同步方法实现同步
class MyThread1 implements Runnable
{
private int ticket=10;
@Override
public void run() {
for(int x =0;x<20;x++)
{
this.sale();
}
}
public synchronized void sale()
{
if(ticket>0) {
System.out.println(Thread.currentThread().getName()+"卖票:"+this.ticket--);
}
}
}
public class SynchronizedThread {
public static void main(String[] args) {
MyThread1 mt = new MyThread1();
new Thread(mt,"票贩子A").start();
new Thread(mt,"票贩子B").start();
new Thread(mt,"票贩子C").start();
new Thread(mt,"票贩子D").start();
}
}
原文:https://www.cnblogs.com/zjw-blog/p/13649612.html