比如:
public class Main
{
public static void main(String[] args)
{
new MyThread().start();
new MyThread().start();
}
}
public class MyThread extends Thread
{
private static int tickets=100;
public void run(){
while(true){
tickets--;
if(tickets>0){
Thread th=Thread.currentThread();//获取当前线程
String na=th.getName();//获取当前线程名字
System.out.println(na+"正在发售第"+tickets+"张票");
}
}
}
}
会导致**资源竞争**的出现,可以使用AtomicInteger来代替
这样的代码流程想实现资源共享是不行的,你的确是new了两个新的线程出来,也开启了两个线程,但是你想一下,是不是两个线程的run方法在自己跑自己的,虽然我并没有运行你这段代码,但是个人觉得会出现这两种情况:
1、两个线程跑出了200的资源;
2、这也是你的静态变量可能起到了作用,出现的类似同步的情况,那就是两个线程有时候会卖出同一张票
说了你的情况之后,那说一下你的这个功能应该怎么实现,用同步(synchronized),同步对象,这样才能真正的实现多窗口同时买票!
我把你的代码改一下,你看一下
public class Main{
public static void main(String[] args){
new MyThread().start();
new MyThread().start();
}
}
public class MyThread extends Thread{
private static int tickets=100;
public void run(){
only();
}
public synchronized void only(){
//同步这个方法,每次只能一个线程访问此方法,
while(true){
tickets--;
if(tickets>0){
String name=Thread.currentThread().getName();//获取当前线程名
System.out.println(name+"正在发售第"+tickets+"张票");
}
}
}
}
内部类用静态变量有意义吗?