马老师的讲解帮助我很好的把理论和实践代码联系起来了。
原则:多线程能使用接口就不使用继承— 灵活。。。。
public class TestThread1{
public static void main(String args[])
{
Runner1 r = new Runner1();
// Thread t = new Thread(r);
t.start();
for(int i=0;i<100;i++)
{
System.out.println("Main Thread:---"+i);
}
}
}
class Runner1 extends Thread{
//class Runner1 implements Runnable{
public void extends Thread{
for(int i=0;i<100;i++)
{
System.out.println("Runner1:"+i);
}
}
}
sleep方法
·可以调用Thread的静态方法:
public static void sleep(long millis)throws
使得当前线程休眠(暂时停止执行millis毫秒)
·由于是静态方法,sleep可以有类名直接调用:
Thread.sleep(…)
public class TestInterrupt{
public static void main(String[] args){
MyThread thread = new MyThread();
thread.start();
try{InterruptedException e} ()
thread.interrupt();//停止线程。泼凉水
}
}
class MyThred extends Thread{
public void run(){
while(true){
System.out.println("=="+new Date()+"==");
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}
yield方法
·让出CPU,给其他线程执行的机会
public class TestYield{
public static void main(String[] args){
MyThread3 t1 = new MyThread3("t1");
MyThread3 t2 = new MyThread3("t2");
t1.start(); t2.start();
}
}
class MyThread3 extends Thread {
MyThread3(String s) {super(s);}
public void run(){
for(int i = 1;i<=100;i++){
System.out.println(getName()+":"+i);
if(i%10==0){
yield();
}
}
}
}
锁 synchronized
public class TestSycn implenents Runnable{
Timer timer = new Timer();
public static void main(String[] args){
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}
class Timer{
private static int num = 0;
public synchronized void add(String name){
//synchroized(this){
num ++;
try {Thread.sleep(1);}
catch(InterruptedException e){}
System.out.println(name+",你是第"+num+"个使用timer的线程");
//}
}
}
输出结果: t1,你是第2个使用timer的线程
t2,,你是第2个使用timer的线程