//执行
New Thread(runnable class).start()执行 runnable calss的run方法。
publicclass helloimplements Runnable {
/**
* @param args
*/
private Stringname;
//构造函数
public hello(){};
public hello(String name){
this.name=name;
}
//
publicvoid run() {
for (int i = 0; i < 3; i++) {
for(int j=0;j<3;j++){
System.out.println(name +"运行 " + i + "行"+ j +"列");
}
}
}
publicstaticvoid main(String[] args) {
//TODO Auto-generated method stub
hello h1=new hello("线程A");
Thread demo= new Thread(h1);
hello h2=new hello("线程B");
Thread demo1=new Thread(h2);
demo.start();
demo1.start();
}
}
运行结果:
线程A运行 0行0列
线程B运行 0行0列
线程A运行 0行1列
线程B运行 0行1列
线程A运行 0行2列
线程B运行 0行2列
class my_threadimplements Runnable{
privateintticket = 5; //5张票
publicvoid run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+"正在卖票"+this.ticket--);
}
}
}
}
publicclass MyThread {
publicstaticvoid main(String [] args) {
my_thread my = new my_thread();
new Thread(my,"1号窗口").start();
new Thread(my,"2号窗口").start();
new Thread(my,"3号窗口").start();
}
}
Thread demo = new Thread(he);
System.out.println("线程启动之前---》" + demo.isAlive());
demo.start();
System.out.println("线程启动之后---》" + demo.isAlive());
class helloimplements Runnable {
publicvoid run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + i);
}
}
publicstaticvoid main(String[] args) {
hello he = new hello();
new Thread(he,"线程").start();
}
}
class helloimplements Runnable {
publicvoid run() {
System.out.println("执行run方法");
try {
Thread.sleep(10000);
System.out.println("线程完成休眠");
} catch (Exception e) {
System.out.println("休眠被打断");
return; //返回到程序的调用处
}
System.out.println("线程正常终止");
}
publicstaticvoid main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he,"线程");
demo.start();
try{
Thread.sleep(2000);
}catch (Exception e) {
e.printStackTrace();
}
demo.interrupt(); //2s后中断线程
}
}
注:
启动进程(进程执行1秒)
进程休眠2秒。
同时多线程要求进程中断
定义:守护线程--也称“服务线程”,在没有用户线程可服务时会自动离开。优先级:守护线程的优先级比较低,用于为系统中的其它对象和线程提供服务。
设置:通过setDaemon(true)来设置线程为“守护线程”;将一个用户线程设置为守护线程的方式是在 线程对象创建 之前 用线程对象的setDaemon方法。
class helloimplements Runnable {
publicvoid run() {
while (true) {
System.out.println(Thread.currentThread().getName() +"在运行");
}
}
publicstaticvoid main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he,"线程");
demo.setDaemon(true);
demo.start();
}
}
class my_threadimplements Runnable{
privateintticket = 5; //5张票
publicvoid run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+"正在卖票"+this.ticket--);
}
}
}
}
publicclass MyThread {
publicstaticvoid main(String [] args) {
my_thread my = new my_thread();
Thread h1=new Thread(my,"1号窗口");
Thread h2=new Thread(my,"2号窗口");
Thread h3=new Thread(my,"3号窗口");
h1.setPriority(5);
h2.setPriority(7);
h3.setPriority(8);
h1.start();
h2.start();
h3.start();
}
}