概念
1、如何用Thread創建多線程?
class MyThreadextends Thread{
private Stringname;
public MyThread(String name){
this.name = name;
}
publicvoid run(){//覆寫Thread中的run()方法
for(int i=0;i<10;i++)
System.out.println("My Thread -->" +name);
}
}
publicclass Test{
publicstaticvoid main(String[] args) {
MyThread t1 = new MyThread("線程1");
MyThread t2 = new MyThread("線程2");
t1.start();
t2.start();
}
}
運行結果
MyThread -->線程1
MyThread -->線程2
MyThread -->線程1
MyThread -->線程2
MyThread -->線程2
MyThread -->線程2
MyThread -->線程1
……
面試題
1、輸出?
public
class
Example
extends
Thread{
@Override
public
void
run(){
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException
e){
e.printStackTrace();
}
System.out.print(
"run"
);
}
public
static
void
main(String[] args){
Example
example=
new
Example();
example.run();
System.out.print(
"main"
);
}
}
答:
用Thread新建一個線程的方法:
(1)新建類,繼承Thread,改寫run();
記憶
當一個優先級高的線程進入就緒狀態,它只是有較高的概率搶到CPU的執行權。
當線程拋出一個例外時,該線程就終止了。