您的位置:首页 > 编程语言 > Java开发

java多线程之接口回调、join方法详解

2018-02-08 19:18 477 查看

join方法

打印完子线程再打印主线程:

public class Demo {
public static void main(String[] args) throws InterruptedException {
JRunnable jr = new JRunnable();
Thread t1 = new Thread(jr);
t1.start();
t1.join();
// 拿到所有的CPU执行权 停在这里执行自己的方法
// 等自己的方法执行完 再把CPU的执行权交回去
/*
* 告诉当前线程(主线程) 我想加入你
* 当前线程把CPU执行权给你
* 等你执行完毕了 当前线程再执行
*/
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
System.out.println("主线程结束");
}
}

class JRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}


接口回调

/*
* 键盘输入
* 1.红色打印
* 2.黑色打印
* 根据输入数字的不同进行打印(打印"接口回调"即可)
*
* 定义一个接口
* 接口方法: 要求可以接收一个字符串做参数
*
* 定义一个功能类
* 要求: 接收一个接口对象作为参数 利用接口对象调用接口方法
*
* 定义两个类 实现接口
* 第1个类 普通打印
* 第2个类 错误(err)打印
*
*/

public class Demo01 {
public static void main(String[] args) {
System.out.println("请输入 1.红色 2.黑色");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
// 创建一个接口的空对象
Inter inter = null;
if (num == 1) {
// 创建打印红色类的对象
inter = new RedPrint();
} else {
// 创建打印黑色类的对象
inter = new BlackPrint();
}
// 使用功能类 (按照不同的对象打印)
PrintClass.print(inter);
}
}

interface Inter{
public abstract void pirntS(String string);
}

// 创建一个功能类 专门负责打印
// 不用管对象是谁 谁调用方法
// 只负责接收一个接口对象 调用接口
class PrintClass {
// 根据传进来不同的对象 调用不同方法
// (多态 增加方法的扩展性)使用接口当参数
public static void print(Inter inter) {
// 调用接口中的方法
inter.pirntS("接口回调");
}
}

// 定义两个类 实现接口
class RedPrint implements Inter{
@Override
public void pirntS(String string) {
System.err.println(string);
}
}

class BlackPrint implements Inter{
@Override
public void pirntS(String string) {
System.out.println(string);
}
}


/*
* 利用接口实现 主线程处理逻辑
* 子线程去读取文件 并打印
*/

public class Demo02 {
public static void main(String[] args) {
// 使用匿名对象方法传参数
Read.printFile(new ReadFileInter() {
// 匿名对象重写的方法
@Override
public void readFile(String string) {
// 打印读取完的文件
System.out.println(string);
}
});
}
}

// 功能类
public class Read {
// 使用接口对象作为参数
public static void printFile(ReadFileInter inter) {
// 开辟线程 读取文件
new Thread(new Runnable() {

@Override
public void run() {
try {
FileReader fr = new FileReader("src/com/lanou3g/hd/Demo02.java");
BufferedReader br = new BufferedReader(fr);
String string = "";
while ((string = br.readLine()) != null) {
inter.readFile(string);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();;
}
}
public interface ReadFileInter {
public abstract void readFile(String string);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息