两种线程的创建方式
1.直接覆盖run方法
Thread thread = new Thread(){
@Override
publicvoid run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
System.out.println("1:"+ Thread.currentThread().getName());
System.out.println("1:"+ this.getName());
}
}
};
2.实现runnable接口
Thread thread2 = new Thread(new Runnable(){//使用runnable更能体现面向对象的思维!
@Override
publicvoid run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) { e.printStackTrace();
}
System.out.println("1:"+ Thread.currentThread().getName());
// System.out.println("1:"+ this.getName());
}
}
});
thread2.start();
实现Runnable接口,Runnable接口中只定义一个run()方法,然后实例化一个 Thread对象时,传入一个实现Runnable接口的对象作为参数,Thread对象会调用Runnable对象的run()方法,进而执行当中所定义的流程。
多线程不会提高程序的运行效率,反而可能降低效率(线程切换需要时间)。
定时器
new Timer().schedule(new TimerTask(){
@Override
publicvoid run() {
System.out.println("bombing!");
}
},4000,3000);//开始四秒后运行,以后每隔三秒运行!
隔时间不同运行
class MyTimerTask extends TimerTask{
@Override
publicvoid run() {
count = (count+1)%2;
System.out.println("bombing!");
new Timer().schedule(new MyTimerTask(), 2000 + 2000*count);
}
}
new Timer().schedule(new MyTimerTask(), 2000);
线程同步
1. 同步代码块,需注意使用的同步对象锁是唯一的
2. 同步方法
publicsynchronizedvoid output2(Stringname){
int len = name.length();
for(int i=0; i<len; i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
publicstaticsynchronizedvoid output3(String name){//使用字节码对象作为锁
int len = name.length();
for(int i=0; i<len; i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
练习经验:要用到共同数据(包括同步锁)的若干个方法应该归在同一个类身上。
class Buziness{
publicbooleanbShouldSub = true;//子方法运行标记
publicsynchronizedvoid sub(int i){
while(!bShouldSub){//如果不是,使用while是未来防止伪唤醒
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}//否则运行
for(int j=1;j<=10;j++)
System.out.println("Sub thread:" + j + " of loop " + i);
bShouldSub = false;//运行完后,更改标记
this.notify();//唤醒另一个线程
}
publicsynchronizedvoid main(int i){
while(bShouldSub){//如果子方法运行标记为真
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}//否则运行
for(int j=1;j<=100;j++)
System.out.println("main thread: " + j + " of loop " + i);
bShouldSub = true;//运行完后,更改标记
this.notify();//唤醒另一个线程
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------