同步条件 ①两个或两个以上 线程对象 用同意堆栈 ② synchronize 锁同一对象
synchrozed (默认)锁的对象是 this
代码验证 :同步条件
class Ticket implements Runnable{
boolean flag = true;
private int tick = 1000;
Object object = new Object();
public void run() {
// TODO Auto-generated method stub
if(flag){
while(true){
synchronized (object) { //synchronized 锁object对象
if(tick > 0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...show..." + tick--);
}
}
}
}
else{
while(true){
show();
}
}
}
public synchronized void show() {
if(tick > 0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...sale..." + tick--);
}
}
}
public class Hello {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
打印结果 会出现:Thread-0...show...0
class Ticket implements Runnable{
boolean flag = true;
private int tick = 1000;
Object object = new Object();
public void run() {
// TODO Auto-generated method stub
if(flag){
while(true){
synchronized (this) {
if(tick > 0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...show..." + tick--);
}
}
}
}
else{
while(true){
show();
}
}
}
public synchronized void show() {
if(tick > 0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...sale..." + tick--);
}
}
}
public class Hello {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
打印结果 :Thread-0...show...1 到此为止