/*
---编写10个线程 第一个线程从1+10 11+20 ......91+100
---最后将10个线程全部相加
*/
import java.util.concurrent.CountDownLatch;//这个类大家可以查阅一下API
class Add implements Runnable
{
CountDownLatch latch;
Add(CountDownLatch latch)
{
this.latch = latch;
}
int sum,a=1,b=10;
public synchronized void run()
{
for (;a<=b;a++)
{
sum = a+sum;
}
System.out.println(sum);
b = b+10;
latch.countDown(); //计数器
}
int GetSum()
{
return sum;
}
}
class ThreadTest1
{
public static void main(String[] args) throws InterruptedException
{
CountDownLatch latch = new CountDownLatch(10);
Add add = new Add(latch);
/*
Thread t1 = new Thread(add);
Thread t2 = new Thread(add);
Thread t3 = new Thread(add);
Thread t4 = new Thread(add);
Thread t5 = new Thread(add);
Thread t6 = new Thread(add);
Thread t7 = new Thread(add);
Thread t8 = new Thread(add);
Thread t9 = new Thread(add);
Thread t10 = new Thread(add);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
*/
for (int a = 0;a<=9;a++) //启动十个线程
{
new Thread(add).start();
}
latch.await(); //计数器为零之前 使当前线程等待
int sum = add.GetSum();
System.out.println("sum="+sum);
}
}
/*
public class CountDownLatchDemo
{
// final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException
{
CountDownLatch latch=new CountDownLatch(2);//两个工人的协作
Worker worker1=new Worker("zhang san", 5000, latch);
Worker worker2=new Worker("li si", 8000, latch);
worker1.start();//
worker2.start();//
latch.await();//等待所有工人完成工作
System.out.println("all work done at "+sdf.format(new Date()));
}
}
static class Worker extends Thread
{
String workerName; //姓名
int workTime; //工作时间
CountDownLatch latch;
public Worker(String workerName ,int workTime ,CountDownLatch latch)
{
this.workerName=workerName;
this.workTime=workTime;
this.latch=latch;
}
public void run()
{
System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));
doWork();//工作了
System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));
latch.countDown();//工人完成工作,计数器减一
}
private void doWork()
{
try
{
Thread.sleep(workTime);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
*/
|
|