搶票線程使用同步塊修改
synchronized(this){};this鎖定的就是這個對象的資源
public class n {
public static void main(String[]args) throws InterruptedException
{
web wb=new web();
new Thread(wb,"a").start();
new Thread(wb,"b").start();
new Thread(wb,"c").start();
}
}
class web implements Runnable{
int num=10;
private boolean flag=true;
public void run()
{
while(flag)
{
test2();
}
}
//修改同步塊
public void test2()
{
synchronized(this)
{
if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
public synchronized void test()
{ if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
集合:
public class n {
public static void main(String[]args) throws InterruptedException
{
web wb=new web();
new Thread(wb,"a").start();
new Thread(wb,"b").start();
new Thread(wb,"c").start();
}
}
class web implements Runnable{
int num=10;
private boolean flag=true;
public void run()
{
while(flag)
{
test2();
}
}
//最優情況
public void test6()
{
if(num<0) //排除沒有票的情況
{
flag=false;
return;
}
synchronized(this)//排除多個線程搶一張票的情況
{
if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
public void test5()
{
if(num<0)
{
flag=false;
return;
}
synchronized(this)//剩一張票時,同樣有三個線程在搶,會出現負數
{
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
public void test4()
{
synchronized(this)
{
if(num<0)
{
flag=false;
return;
} } //再判斷完后,同樣會出現多個線程搶一張票的情況
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
public void test3()
{
synchronized((Integer)num) //鎖定必須鎖對象,并且鎖定的是對象地址,對象1,2,3的地址
//不同,所以鎖不住
{
if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
//修改同步塊
public void test2()
{
synchronized(this)
{
if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
public synchronized void test()
{ if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。