三个线程轮流打印1-100
/**
* @Description: 两个线程轮流打印1-100 思路:声明变量然后将变量锁定,线程轮流访问变量打印。线程之间的同步和通信
* @author WDY
* @date 2016年11月24日
*/
public class ThreadTest implements Runnable{
int i=0;
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
Thread thread1 = new Thread(threadTest);
Thread thread2 = new Thread(threadTest);
Thread thread3 = new Thread(threadTest);
thread1.setName("线程1");
thread2.setName("线程2");
thread3.setName("线程3");
thread1.start();
thread2.start();
thread3.start();
}
@Override
public void run() {
while (true) {
synchronized (this) {
notify();
try {
Thread.currentThread();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i<=100) {
System.out.println(Thread.currentThread().getName()+":"+i);
i++;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
- 现在可以实现轮流打印了,但是如果我们让三个线程按顺序去打印改怎么实现呢?比如线程1打印1,2,3线程2打印4,5,6依次类推。
- 代码实现
/**
* @Description: 三个线程,线程1打印1-5,线程2打印6-10,线程3打印11-15
* @author WDY
* @date 2016年11月28日
*/
public class ThreadTest2 {
static class TempObject{
private int id;
private int count;
public TempObject(int id, int count) {
super();
this.id = id;
this.count = count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public synchronized void print(int num){
for (int i = 0; i < count; i++) {
System.out.println("Thread" + id + ":" + num++);
}
}
}
static class selfRunnable implements Runnable{
private TempObject pre;
private TempObject self;
private static int num=1;
public selfRunnable(TempObject pre, TempObject self) {
super();
this.pre = pre;
this.self = self;
}
@Override
public void run() {
while (num <= 75) {
System.out.println("p:"+pre.getId()+";s:"+self.getId()+";p-"+num);
synchronized (pre) {
System.out.println("p:"+pre.getId()+";s:"+self.getId()+";s-"+num);
synchronized (self) {
self.notify();
self.print(num);
num += self.getCount();
}
try {
pre.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (self) {
self.notify();
}
}
}
public static void main(String[] args) throws InterruptedException {
TempObject tempObject1=new TempObject(1, 5);
TempObject tempObject2=new TempObject(2, 5);
TempObject tempObject3=new TempObject(3, 5);
new Thread(new selfRunnable(tempObject3, tempObject1)).start();;
Thread.sleep(100);
new Thread(new selfRunnable(tempObject1, tempObject2)).start();;
Thread.sleep(100);
new Thread(new selfRunnable(tempObject2, tempObject3)).start();;
Thread.sleep(100);
}
}
*参考内容
链接
链接