public class Test {
public static void main(String[] args) {
MyThread st1=new MyThread();
new Thread(st1).start();
new Thread(st1).start();
}}class MyThread extends Thread{
private int ticket = 5; // 一共5张票 public void run() {
for (int i = 0; i < 50; i++)
if (this.ticket > 0)
System.out.println("卖票:ticket= " +Thread.currentThread().getName()+ this.ticket--);
}
}
网上说实现Thread不能资源共享,但我觉得上面代码实现了ticket在线程间共享啊,求高手解答!
public static void main(String[] args) {
MyThread st1=new MyThread();
new Thread(st1).start();
new Thread(st1).start();
}}class MyThread extends Thread{
private int ticket = 5; // 一共5张票 public void run() {
for (int i = 0; i < 50; i++)
if (this.ticket > 0)
System.out.println("卖票:ticket= " +Thread.currentThread().getName()+ this.ticket--);
}
}
网上说实现Thread不能资源共享,但我觉得上面代码实现了ticket在线程间共享啊,求高手解答!
线程资源共享必须加锁
我这一个多线程售票系统的,你研究一下public class TicketsSystem{
public static void main(String[] args){
Sale sale = new Sale();
new Thread(sale).start();
new Thread(sale).start();
new Thread(sale).start();
new Thread(sale).start();
}
}
class Sale implements Runnable{
int tickets=100;
Object o = new Object();
public void run(){
while(true){
/**
synchronized(o){
if(tickets >0){
try{
Thread.sleep(10);
}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+" cell tickets:"+tickets);
tickets--;
}
}
*/
cell();
}
}
private synchronized void cell(){
if(tickets >0){
try{
Thread.sleep(10);
}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+" cell tickets:"+tickets);
tickets--;
}
}
}
new Thread(st1).start();
new Thread(st1).start();
你这里虽然启动了两个线程,但是传的是同一个Runnable对象的引用
如此一来ticket在线程间共享没什么奇怪的,因为ticket本身就在堆中
public class Test {
public static void main(String[] args) {
MyThread st1=new MyThread();
new Thread(st1).start();
new Thread(st1).start();
}}class MyThread implements Runnable{
private int ticket = 5; // 一共5张票 public void run() {
for (int i = 0; i < 50; i++)
if (this.ticket > 0)
System.out.println("卖票:ticket= " +Thread.currentThread().getName()+ this.ticket--);
}
}
但我觉得这两种用法并没有区别。
网上是指?
我感觉也是一样的啊。线程是用来驱动任务的,我们用两个线程来驱动同一个任务,应该和 任务是如何定义的无关吧?
这里我们通过 继承Thread 和实现 Runnable 来定义任务。 两个线程来同时驱动一个任务,当然涉及到共享的问题啦。 但是和任务如何定义无关啊
楼主本意是想把ticket实现多线程共享吧,把ticket定义为private static int ticket = 5, 就可以线程共享了。
你的理解是对的,在你的代码中,两段代码没什么区别,因为最终是两个new Thread线程对象,共同访问new MyThread对象资源。javadoc文档里很明确的说明了,class Thread 是 implements Runnable的,所以你的MyThread是extends Thread 还是 implements Runnable,在你的代码中没什么区别。