Java学习笔记——多线程(二)
2017-08-17 12:35
429 查看
//继承Thread实现线程,开启多个线程,验证是否共享同一资源(属性值)
public class Demo04_Thread extends Thread {private int ticket = 5;
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat();
for (int i = 0; i <= 20; i++) {
if (ticket > 0) {
System.out.println("时间:" + sdf.format(new Date()) + "name" + Thread.currentThread().getName()
+ "正在卖票..." + (this.ticket--));
}
}
}
public static void main(String[] args) {
Demo04_Thread tt = new Demo04_Thread();
tt.setName("窗口1");
tt.start();
new Demo04_Thread().start();
new Demo04_Thread().start();
}
}
//接口方式实现线程,开启多个线程,验证是否共享同一资源(属性值)
public class Demo05_Thread implements Runnable {private int ticket = 5;
public void run() {
saleTicket();
}
// 卖票的方法
public void saleTicket() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSSS");
System.out.println("时间:" + sdf.format(new Date()));
for (int i = 10; i <= 20; i++) {
if (this.ticket > 0) {
System.out.println("时间:" + sdf.format(new Date()) + "name" + Thread.currentThread().getName()
+ "正在卖票..." + (this.ticket--));
}
}
}
public static void main(String[] args) {
Demo05_Thread myRunTicket = new Demo05_Thread();
Thread tt = new Thread(myRunTicket);
tt.setName("窗口1");
new Thread(myRunTicket, "窗口2").start();
new Thread(myRunTicket, "窗口3").start();
tt.start();
// 验证是否共享同一资源
}
}
相关文章推荐
- JAVA多线程学习笔记
- java多线程学习笔记2
- 学习java多线程的笔记3-使用BlockingQueue阻塞队列来模拟两个线程之间的通信
- 黑马程序员---java多线程 学习笔记
- 训练营学习笔记 java多线程(五)生产者/消费者
- 学习笔记7—Java基础5_多线程
- Java学习笔记(五、多线程)
- Java学习笔记9——多线程
- 黑马程序员之JAVA学习笔记:多线程学习大总结
- 学习java多线程的笔记5--初体验
- JAVA学习笔记————多线程
- java学习笔记(九)----多线程
- java学习笔记1017---多线程
- 学习笔记 java 多线程(二)
- 黑马程序员java学习笔记之四(java多线程总结)
- Java多线程学习笔记
- [零散篇]Java学习笔记---Java的Socket网络编程以及多线程
- 学习笔记 java多线程 信号量(Semaphore),死锁
- Java 多线程编程 学习笔记
- 学习java多线程的笔记1--Thread(Runnable t)与重写run()方法等