多线程控制实例

题目: 有三个线程分别负责打印数字,按照如下规律打印:

Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Thread3: 11
Thread3: 12
Thread3: 13
Thread3: 14
Thread3: 15
Thread1: 16
Thread1: 17
Thread1: 18
Thread1: 19
Thread1: 20
Thread2: 21
Thread2: 22
Thread2: 23
Thread2: 24
Thread2: 25


新建打印类:

package com.yf.service;




/**
File: Printer.java
Description: 打印服务类
@author 
@date 2016年10月21日 下午2:14:46
@version 1.0 
**/


public class Printer {

private int printNum = 1;
private int lock = 0;

synchronized public void print1() throws Exception{
while(printNum<=75){
if(lock != 0){
wait();
}else{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + printNum);
printNum ++;
}
//Thread.sleep(2000);
lock = 1;
notifyAll();
}
}


}

synchronized public void print2() throws Exception{
while(printNum<=75){
if(lock != 1){
wait();
}else{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + printNum);
printNum ++;
}
//Thread.sleep(2000);
lock =2;
notifyAll();
}
}

}

synchronized public void print3() throws Exception{
while(printNum<=75){
if(lock != 2){
wait();
}else{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + printNum);
printNum ++;
}
//Thread.sleep(2000);
lock = 0;
notifyAll();
}
}
}
}


新建3个线程类:

public class Thread1 implements Runnable{

private Printer printer;

public Thread1(Printer printer) {
super();
this.printer = printer;
}

@Override
public void run() {
try {
printer.print1();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


public class Thread2 implements Runnable {
private Printer printer;

public Thread2(Printer printer) {
super();
this.printer = printer;
}

@Override
public void run() {
try {
printer.print2();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


public class Thread3 implements Runnable{
private Printer printer;

public Thread3(Printer printer) {
super();
this.printer = printer;
}

@Override
public void run() {
try {
printer.print3();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


新建测试调用:

Printer printer1 = new Printer();
Thread thread1 = new Thread(new Thread1(printer1));
thread1.setName("Thread1");
thread1.start();

Thread2 runnable = new Thread2(printer1);
Thread thread2 = new Thread(runnable);
thread2.setName("Thread2");
thread2.start();


Thread3 runnable3 = new Thread3(printer1);
Thread thread3 = new Thread(runnable3);
thread3.setName("Thread3");
thread3.start();


通过控制lock锁来达到依次调用print输出


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值