黑马程序员技术交流社区
标题:
java多线程_票售问题
[打印本页]
作者:
徐西宏
时间:
2011-8-29 14:07
标题:
java多线程_票售问题
java多线程_票售问题
以下是本人调试的售票代码 为什么运行一次后cpu就百分之百了,而eclipse就死了,求优化。。。
package cn.xu.thread;
class Ticket implements Runnable{
private int tickets =100;
public void run() {
while(true){
if(tickets>0)
System.out.println(Thread.currentThread().getName()+" "+ tickets--);
}
}
}
public class ThreadDemo01 {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
作者:
匿名
时间:
2011-8-29 14:19
代码给你改了一下 你没有跳出循环的语句啊,while永远为true了不是么。还有 线程的话 应该加入wait()执行,实现同步与死锁,你这个代码现在没加到是没什么 但以后做大程序了都要加入 不然会产生错误[code=java]class Ticket implements Runnable{
private int tickets = 100;
public void run(){
while(true){
if(tickets>0){
System.out.println(Thread.currentThread().getName()+" "+ tickets--);
}else{
break;
}
}
}
}
public class ThreadDemo01{
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
} [/code]
作者:
匿名
时间:
2011-8-29 16:24
[code] package cn.xu.thread;
class Ticket implements Runnable{
private int tickets =100;
public void run() {
while(true){
lock();
if(tickets>0)
System.out.println(Thread.currentThread().getName()+" "+ tickets--);
unlock();
} else{
break;
}
}
}
public class ThreadDemo01 {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
} [/code]
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2