- public static void main(String[] args) {
- ThreadGroup g=new ThreadGroup("test");
- Thread t=null;
- for(int i=0;i<1000;i++)
- {
- t=new Thread(g,new R_impl(),i+"");
- t.start();
- }
- }
- class R_impl implements Runnable
- {
- public static int count=1;
- //public volatile int count=1;
- public static Lock myLock=new ReentrantLock();
- public static Condition cond=myLock.newCondition();
- public static Object obj=new Object();
-
- public void run() // public volatile int count=1;
- {
- try
- {
- count--;
- System.out.println(count);
- count++;
- System.out.println(count);
- }catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
- {
- try
- {
- synchronized (obj) {
- count--;
- System.out.println(count);
- count++;
- System.out.println(count);
- }
- }catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
- public synchronized void run()
- {
- try
- {
- if(count<=0)
- this.wait();
- count--;
- System.out.println(count);
- count++;
- this.notifyAll();
- System.out.println(count);
- }catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
- public void run()
- {
- try
- {
- myLock.lock();
- count--;
- System.out.println(count);
- count++;
- System.out.println(count);
- myLock.unlock();
- }catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
- public void run()
- {
- myLock.lock();
- try
- {
- if(count<=0)
- cond.await();
- count--;
- System.out.println(count);
- count++;
- System.out.println(count);
- cond.signalAll();
- }catch(Exception ex)
- {
- ex.printStackTrace();
- }finally
- {
- myLock.unlock();
- }
- }
- }
JAVA线程同步
最新推荐文章于 2024-07-22 14:15:06 发布