线程,线程同步,对象锁,同步方法
/**
* @author Administrator 模拟火车站卖票窗口 用实现的方式,此时的Ticket只是一个普通的类 在用实现的方式的时候,必须要
* implements Runnable 接口
*/
public class Ticket implements Runnable {
int count = 100;
Object obj = new Object();
//
@Override
public void run() {
while (true) {
// 线程同步,能保证共享数据的安全,给一个对象锁,其类型是Object的即可,但是要保证是同一个
// 用对象锁实现线程的同步,以保证数据的安全
/*
* synchronized (this.getClass()) {
*
* if (count > 0) {
* System.out.println(Thread.currentThread().getName() + "卖出票号为" +
* count--); } else { break; }
*
* }
*/
// 用同步方法实现线程的同步
show();
}
}
if (count > 0) {
System.out.println(Thread.currentThread().getName() + "卖出票号为" + count--);
} else {
return;
}
}
/**
* @author Administrator 模拟火车站卖票窗口 用实现的方式,此时的Ticket只是一个普通的类 在用实现的方式的时候,必须要
* implements Runnable 接口
*/
public class Ticket implements Runnable {
int count = 100;
Object obj = new Object();
//
@Override
public void run() {
while (true) {
// 线程同步,能保证共享数据的安全,给一个对象锁,其类型是Object的即可,但是要保证是同一个
// 用对象锁实现线程的同步,以保证数据的安全
/*
* synchronized (this.getClass()) {
*
* if (count > 0) {
* System.out.println(Thread.currentThread().getName() + "卖出票号为" +
* count--); } else { break; }
*
* }
*/
// 用同步方法实现线程的同步
show();
}
}
//同步方法加关键字 synchronized 将需要同步的代码写到同步方法中(共享数据)
public synchronized void show() {if (count > 0) {
System.out.println(Thread.currentThread().getName() + "卖出票号为" + count--);
} else {
return;
}
}
}
/**
* 测试类
*
* @author Administrator
*
*/
public class Test_Ticket {
public static void main(String[] args) {
// 创建一个票窗口
Ticket ticket = new Ticket();
// new Thread(Runable r,String name) 可以创建一个线程 别给其起名字
// 创建窗口1
Thread thread1 = new Thread(ticket, "窗口1");
// 创建窗口2
Thread thread2 = new Thread(ticket, "窗口2");
// 创建窗口3
Thread thread3 = new Thread(ticket, "窗口3");
// 开始线程
thread1.start();
thread2.start();
thread3.start();
}
}