JavaWork_線程同步及併發控制的問題

JavaWork_線程同步及併發控制的問題
//模擬售票系統,4個窗口同時售100張票(index)
//1)使用new Thread()創建線程
class ThreadDemo1
{
 public static void main(String[] args)
 {
  new TestThread().start();
  new TestThread().start();
  new TestThread().start();
  new TestThread().start();
 }
}

class TestThread extends Thread
{
 int index = 100;
 public void run()
 {
  wile(index >= 100)
   System.out.println("Run" + Thread.currentThread().getName() + "is Soing " + index--);
 }
}
//2)
class TreadDemo1
{
 public static void main(String[] args)
 {
  TestThread tt = new TestThread();
  tt.start();
  tt.start();
  tt.start();
  tt.start();
 }
}

class TestThread extends Thread
{
 int index = 100;
 public void run()
 {
  while(index >= 0)
  System.out.println("Run" + Thread.currentThread().getName() + "is Soling " + index--);
 }
}

/////////////////////////////////////////
class ThreadDemo1
{
 public static void main(String[] args)
 {
  TestThread tt = new TestThread();
  new Thread(tt).start();
  new Thread(tt).start();
  new Thread(tt).start();
  new Thread(tt).start();
 }
}

class TestThread implements Runnable
{
 int index = 100;
 public void run()
 {
  while(index >= 0)
   System.out.println("Run" + Thread.currentThread().getName() + "is Soling " + index--);
 }
}



//////////////////////線程併發控制問題
class TreadDemo1
{
 public static void main(String[] args)
 {
  TestThread tt = new TestThread();
  new Thread(tt).start();
  new Thread(tt).start();
  new Thread(tt).start();
  new Thread(tt).start();
 }
}

class TestThread implements Runnable
{
 int index = 100;
 String str = new String("");
 public void run()
 {
  
   while(true)
   {
    synchronized(str)//保持線程原子性,參數爲任意對象
    {
     if (index > 0)
     {
      try{Thread.sleep(10);}catch(Exception e){}
      System.out.println("Run" + Thread.currentThread().getName() + "is Soling " + index--);
       } 
    }
   }
  
 }
}
//一般情況下不要使用併發控制,會犧牲cpu爲代價
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章