十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
并發(fā):
同一個對象對多個線程同時操作
線程同步:一種等待機制,等待前面線程使用完再下一個線程使用
線程同步形成條件:形成隊列,加上鎖機制(synchronized)
同步塊:synchronized(具體對象){代碼};鎖定資源,一個線程一個線程的使用

讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價值的長期合作伙伴,公司提供的服務(wù)項目有:域名注冊、虛擬主機、營銷軟件、網(wǎng)站建設(shè)、公主嶺網(wǎng)站維護、網(wǎng)站推廣。
搶票:
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)
{
test();
}
}
public synchronized void test()//鎖的是對象的資源,即this成員,讓資源每次只被一個線程使用,然后下次靠cpu調(diào)度,而不讓
//一份資源同時被多個線程使用
{ if(num<0)
{
flag=false;
return;
}
try {
Thread.sleep(200);
}catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);
//線程不安全,可能都都是同一張票,可能票是負數(shù)
//負數(shù):當(dāng)還有1張票時,三個線程同時進入,都等待后,有兩個線程為負數(shù)
//相同票:線程有自己的工作臺,多個線程幾乎同時到達,拷貝數(shù)據(jù)
}
}取錢:
public class el {
public static void main(String[]args)
{
account a=new account(100,"me");
get g=new get(a,80,"she");
get g2=new get(a,90,"he");
g.start();
g2.start();
}
}
//賬戶
class account {
int money;
String name;
public account(int money,String name)
{
this.money=money;
this.name=name;
}
}
//模擬取款
class get extends Thread
{
account a; //取錢的賬戶
int getmoney; //單個人取的錢數(shù)
int getall; //多個人取的總數(shù)
public get (account a,int getmoney,String name)
{
super(name);//Thread可以設(shè)置name
this.a=a;
this.getmoney=getmoney;
}
public void run()
{
test();
}
public /*synchronized */void test()//鎖定失敗,不應(yīng)該鎖this,而應(yīng)該鎖account
{//因為a.money是account里的,總錢數(shù)應(yīng)該每次由一個線程調(diào)用,而不是多個線程
//使用同步塊鎖定
if(a.money<=0)
{
return;
}
synchronized(a){
if(a.money-getmoney<0) //添加也沒用
{
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.money-=getmoney;
getall+=getmoney;
System.out.println(this.getName()+"-->賬戶余額為:"+a.money);
System.out.println(this.getName()+"-->取錢總數(shù)為:"+getall);
}
}
}容器:
public class h {
public static void main(String[]args)
{
List list=new ArrayList();
for(int i=0;i<10000;i++)
{
new Thread(()->
{synchronized(list) {
list.add(Thread.currentThread().getName());}}
).start();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(list.size());
}
}