Thead class
线程开启不一定立即执行由CPU决定
package duoxiancheng;
public class testThread extends Thread{
@Override
public void run() {
//run方法线程
for (int i=0;i<20;i++){
System.out.println("我在看代码"+i);
}
}
public static void main(String[] args) {
//main主线程
//创建一个线程
testThread testThread = new testThread();
testThread.start();
for (int i=0;i<20000;i++){
System.out.println("我在看视频————————"+i);
}
}
}
Runnable接口
package test;
public class testRunable implements Runnable {
@Override
public void run() {
for (int i=0;i<20;i++){
System.out.println("我看见你了"+i);
}
}
public static void main(String[] args) {
//创建Runna接口实现类
testRunable testRunable = new testRunable();
//创建线程对象,通过线程对象来开启代理
Thread thread = new Thread();
thread.start();
new Thread(testRunable).start();
for (int i=0;i<2000;i++){
System.out.println("我看见你了____"+i);
}
}
}
模拟龟兔赛跑
package test;
public class race implements Runnable {
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 1000; i++) {
if (Thread.currentThread().getName().equals("兔子")&& i%10==0){ // 模拟兔子睡觉,睡觉在10步以后每次睡觉1毫秒
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameover(i); //判断比赛是否结束
if (flag){
break;
} System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
private boolean gameover(int steps){
if (winner!=null){
return true;
}{
if (steps>=1000){
winner = Thread.currentThread().getName();
System.out.println("胜利者是"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
race race = new race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
静态代理
演示静态代理
package test;
public class StaticProxy {
public static void main(String[] args) {
Wedding wedding = new Wedding(new You());
wedding.marry();
}
}
interface Marry{
void marry();
}
//真实角色
class You implements Marry{
@Override
public void marry() {
System.out.println("今天结婚了");
}
}
//代理角色 ,帮助你
class Wedding implements Marry{
//找到代理真实对象角色
private Marry target;
public Wedding(Marry target) {
this.target = target;
}
@Override
public void marry() {
before();
this.target.marry();
after();
}
private void after() {
System.out.println("付钱");
}
private void before() {
System.out.println("结婚前布置会场");
}
}
总结
-
真实对象和代理对象要实现同一个接口
-
代理对象要代理真实角色
-
好处
- 代理对像有很多做不了的事
- 真实对象专心做自己的事情