举的例子不合适,容易误导别人!继承thread的子类中定义了票数变量,每new一下启动新线程,都会有5张票,把票数变量定义成全局变量试试
2016-03-13
class MyThread implements Runnable{
Lock lock = new ReentrantLock();
private int number=5;
@Override
public void run() {
lock.lock();
try{
while(number >0){
number--;
System.out.println(Thread.currentThread().getName()+"卖一张剩余票数:"+number);
}
}finally{
lock.unlock();
}
}}要加锁机制
Lock lock = new ReentrantLock();
private int number=5;
@Override
public void run() {
lock.lock();
try{
while(number >0){
number--;
System.out.println(Thread.currentThread().getName()+"卖一张剩余票数:"+number);
}
}finally{
lock.unlock();
}
}}要加锁机制
2016-02-27
thread代码里主函数那对象实例化和Runnable代码里的主函数对象实例化的代码都不一样,前提条件都不一样,咋比出thread和Runnable的不同啊。
而且我把ticketsRunnable里面的代码implements Runnable换成extends Thread,执行效果一样啊,那Thread和Runnable还有啥区别啊。
而且我把ticketsRunnable里面的代码implements Runnable换成extends Thread,执行效果一样啊,那Thread和Runnable还有啥区别啊。
2016-01-26