您好,登錄后才能下訂單哦!
搶票線程使用同步塊修改
synchronized(this){};this鎖定的就是這個(gè)對(duì)象的資源
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();
}
}
//最優(yōu)情況
public void test6()
{
if(num<0) //排除沒(méi)有票的情況
{
flag=false;
return;
}
synchronized(this)//排除多個(gè)線程搶一張票的情況
{
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)//剩一張票時(shí),同樣有三個(gè)線程在搶,會(huì)出現(xiàn)負(fù)數(shù)
{
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;
} } //再判斷完后,同樣會(huì)出現(xiàn)多個(gè)線程搶一張票的情況
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
}
public void test3()
{
synchronized((Integer)num) //鎖定必須鎖對(duì)象,并且鎖定的是對(duì)象地址,對(duì)象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--);
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。