Thread 初探

     对线程了解不多,且不经常去用,最近想起,小小了解,且做个小demon和大家分享一下。

demon:两个线程,分别交替打印20次后中断。

      package com.cn.ld.exercises;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Administrator
 * Exercise
 * 2011-9-22 下午04:55:55 
 * Description:
 */
public class Test {
 private static AtomicInteger s_count = new AtomicInteger(0);
 private static boolean stop ;
 private static int n = 0 ;
 private static int n1 = 0;
 private static int n2 = 0;
 public Test(boolean stop){
  this.stop = stop ;
 }
 public class thread1 implements Runnable {
  public  boolean stop= false ;
        public thread1(boolean  stop){
         this.stop = stop ;
        }
        public boolean  getStop(){
         return stop ;
        }
  public void run() {
   synchronized (s_count) {
    
    while (!stop) {
     if(n2==21&&n1==21){
      try {
       Thread.sleep(10000);
       stop = true ;
       Thread.interrupted();
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     if (n % 2 != 0) {
        System.out.println(Thread.currentThread().getName()
        + ":运行了" + n1 + "次!");
      n++ ;
      n1++;
      s_count.notify();
     } else {
      try {
       s_count.wait();
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
    }
   }
  }

 }

 public class thread2 implements Runnable {
  public  boolean stop= false ;
        public thread2(boolean  stop){
         this.stop = stop ;
        }
        public boolean  getStop(){
         return stop ;
        }
  public void run() {
   synchronized (s_count) {
    
    while (!stop) {
     if(n2==21&&n1==21){
      try {
       Thread.sleep(10000);
       stop = true ;
       Thread.interrupted();
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      
     }
     if (n % 2 == 0) {
      System.out.println(Thread.currentThread().getName()
         + ":运行了" + n2 + "次!");
      n++;
      n2++;
      s_count.notify();
     } else {
      try {
       s_count.wait();
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
    }
   }
  }

 }

 public static void main(String[] args) throws InterruptedException {
  Test test = new Test(false);
  Thread t1 = new Thread(test.new thread1(test.stop));
  Thread t2 = new Thread(test.new thread2(test.stop));
     t1.start();
     t2.start();
 }
}

 

写的很丑陋,还请见谅,大家尽可怕转

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值