线程强制运行

可以使用join()方法让一个线程强制运行,线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行。

范例:线程的强制运行

package test1;

import javax.xml.ws.soap.MTOM;

class MyThread5 implements Runnable {
	public void run() {
		for (int i = 0; i < 3; i++) {// 覆写run方法
			System.out.println(Thread.currentThread().getName() + "运行,i=" + i);// 取得当前线程的名称
		}
	}
}

public class ThreadDemoName01 {
	public static void main(String[] args) {
		MyThread5 my = new MyThread5();
		Thread t = new Thread(my, "线程");
		System.out.println("线程开始执行之前-->" + t.isAlive());// 判断是否启动
		t.start();
		System.out.println("线程开始之后-->" + t.isAlive());// 判断是否启动

		for (int i = 0; i < 50; i++) {
			if (i > 10) {
				try {
					t.join();// 线程T进程强制运行
				} catch (Exception e) {
				}
			}
			System.out.println("main运行-->" + i);
		}
		System.out.println("代码执行之后-->" + t.isAlive());
	}
}

 范例: 线程休眠

package test1;

import javax.xml.ws.soap.MTOM;

class MyThread5 implements Runnable {
	public void run() {
		for (int i = 0; i < 3; i++) {// 覆写run方法
			System.out.println(Thread.currentThread().getName() + "运行,i=" + i);// 取得当前线程的名称
		}
	}
}

public class ThreadDemoName01 {
	public static void main(String[] args) {
		MyThread5 my = new MyThread5();
		Thread t = new Thread(my, "线程");
		System.out.println("线程开始执行之前-->" + t.isAlive());// 判断是否启动
		t.start();
		System.out.println("线程开始之后-->" + t.isAlive());// 判断是否启动

		for (int i = 0; i < 50; i++) {
			if (i > 10) {
				try {
					Thread.sleep(500);// 线程休眠
				} catch (Exception e) {
				}
			}
			System.out.println("main运行-->" + i);
		}
		System.out.println("代码执行之后-->" + t.isAlive());
	}
}

中断线程 使用interrupt()方法中断运行状态 

后台线程:使用setDaemon()方法即可 ,例如:t.setDaemon(true);

 

 

posted on 2011-12-09 11:09  wangbokun  阅读(306)  评论(0编辑  收藏  举报

导航