对线程了解不多,且不经常去用,最近想起,小小了解,且做个小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();
}
}
写的很丑陋,还请见谅,大家尽可怕转