Thread是线程,Runnable是线程所执行的代码,相对来说第二种更符合面向对象。
思考:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("-----");
}
}){
public void run() {
System.out.println("++++++");
};
}.start();
输出什么?
-------------------
面试遇到的题目:写个程序,实现每隔2S执行A程序,再隔4S继续执行A程序:
一看题目用定时器解决,先用定时器写个基础的出来,难点在
package thread;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
static int i=0;
public static void main(String[] args) {
class MyTimerTask extends TimerTask{
@Override
public void run() {
i++;
System.out.println("excute A!");
new Timer().schedule(new MyTimerTask(), i%2==0?2000:4000);
}
}
new Timer().schedule(new MyTimerTask(), 2000);
while(true){
System.out.println(Calendar.getInstance().get(Calendar.SECOND));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TimerTask timerTask = new TimerTask() {
// @Override
// public void run() {
// System.out.println("sdafdfsdff");
// i++;
// }
// };
// Timer timer = new Timer();
// int time=3000;
// if(i%2==0){
// time=3000;
// }else{
// time=5000;
// }
// System.out.println("time:"+time);
// timer.schedule(timerTask, 0,time);
//// timer.cancel();
//// timer.
}
}
多线程的同步互斥与通信,