VolRunnable关键词
子线程修改的值 同步到主线程中
代码示例:
public class Demo04 {
public static void main(String[] args) {
VolRunnable runnable = new VolRunnable();
Thread thread = new Thread(runnable);
thread.start();
// 子线程修改的值 没有同步到主线程中
while (!runnable.isOver) {
}
System.out.println("结束");
}
}
class VolRunnable implements Runnable{
// volatile 可以把线程中的值修改后立即同步出去
public volatile boolean isOver = false;
private int num = 0;
@Override
public void run() {
while (!isOver) {
num ++;
// 把线程执行时间加大
// 防止上面 还没执行到循环处 这里的标记值就改了
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
if (num == 5) {
isOver = true;
}
}
}
}
join()
告诉当前线程 调用join的线程想加入
代码示例:
public class Demo01 {
public static void main(String[] args) {
JRunnable runnable = new JRunnable();
Thread thread = new Thread(runnable);
thread.start();
try {
/*
* 告诉当前线程 调用join的线程想加入
* 当前线程将CPU执行权交给调用join的线程 等该线程执行完毕
* 把CPU的执行权交还回去 当前线程在执行
*/
thread.join(); // 拿到所有的CPU执行权 停在这里
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
System.out.println("main is over");
}
}
class JRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
}
接口回调
import java.util.Scanner;
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 void prints(String string);
}
class RedPrint implements Inter{
@Override
public void prints(String string) {
System.err.println(string);
}
}
// 创建一个功能类 专门负责打印
// 根本不用管 对象是谁 更不用管 谁调用什么方法
// 只负责接收一个接口对象 调用接口方法
class PrintClass {
// 根据传进来不同的对象 调用不同的方法
// 多态好处:增加方法的扩展性
// 使用接口当参数
public static void print(Inter inter) {
// 调用接口中的方法
inter.prints("接口回调");
}
}
class BlackPrint implements Inter{
@Override
public void prints(String string) {
System.out.println(string);
}
}