一、構造多線程類
1、繼承Thread類
package multithread;
public class TestThread01 {
public static void main(String[] args) {
Thread th = new FirstThread();
th.start();
for(int i=0; i<100; i++){
System.out.println("main:"+i);
}
}
}
class FirstThread extends Thread{
@Override
public void run() {
for(int i=0; i<100; i++){
System.out.println("first:"+i);
}
}
}
2、實現Runnable接口
package multithread;
public class TestThread02 {
public static void main(String[] args) {
new TestThread02().begin();
}
public void begin(){
MyThread th = new MyThread();
Thread t = new Thread(th);
t.start();
for(int i=0; i<100; i++){
System.out.println("first:"+i);
}
}
class MyThread implements Runnable{
@Override
public void run() {
for(int i=0; i<100; i++){
System.out.println("first:"+i);
}
}
}
}
開發中一般採用實現Runnable接口的方式,因爲類只能單繼承,如果一個類集成了Thread,那麼它就不能繼承其他類。這在開發中很不靈活。
3、兩種方法的變量的不同
package multithread;
public class TestThread01 {
public static void main(String[] args) {
//每個線程都有自己的成員變量空間
Thread th = new FirstThread("mt1");
th.start();
Thread th1 = new FirstThread("mt2");
th1.start();
}
}
class FirstThread extends Thread{
public FirstThread(String name){
super(name);
}
private int index = 0;
@Override
public void run() {
for(; index <100; index++){
System.out.println(Thread.currentThread().getName()+":"+index);
}
}
}
結果:每個線程的index都是從0到99
package multithread;
public class TestThread02 {
public static void main(String[] args) {
new TestThread02().begin();
}
public void begin(){
//共享mt中的成員變量
MyThread th = new MyThread();
new Thread(th,"mt1").start();
new Thread(th,"mt2").start();
}
class MyThread implements Runnable{
private int index = 0;
@Override
public void run() {
for(; index<100; index++){
System.out.println(Thread.currentThread().getName()+":"+index);
}
}
}
}
結果:兩個線程的index相互增加輸出。
啓動線程
new Thread(xxx).start();
啓動線程要用 start 方法
如果使用 run方法,只是簡單的執行 run方法而已,沒有啓動一個線程。
停止線程
1、stop方法 (Deprecated)
package multithread;
public class TestThreadStop {
public static void main(String[] args) {
new TestThreadStop().begin();
}
public void begin(){
MyThread mt = new MyThread();
Thread tmt = new Thread(mt,"mt1");
tmt.start();
while(true){
if(mt.index==500){
//讓線程停止, 該方法已經被淘汰了,因爲不安全,不會釋放資源,因爲線程雖然停止,但是線程裏的方法可能還在運行
tmt.stop();
break;
}
}
}
class MyThread implements Runnable{
private int index = 0;
@Override
public void run() {
for(; index<1000; index++){
System.out.println("index:"+index);
}
}
}
}
2、正確方法
package multithread;
public class TestThreadStop {
public static void main(String[] args) {
new TestThreadStop().begin();
}
public void begin(){
MyThread mt = new MyThread();
Thread tmt = new Thread(mt,"mt1");
tmt.start();
while(true){
if(mt.index>2000){
mt.stopThread();
System.out.println("------------");
break;
}
}
}
class MyThread implements Runnable{
private int index = 0;
private boolean flag = true;
@Override
public void run() {
for(; index<10000; index++){
if(!flag){
break;
}
System.out.println("index:"+index);
}
}
public void stopThread(){
//在這個位置釋放資源 ** 這個很重要
flag = false;
}
}
}
我的計算機是四核的所以模擬不出被停止的現象。