1. extends Thread类
class Mythread extends Thread {
public String name = null;
public Mythread(String name){
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + i);
}
}
}
public class Dthread extends Thread {
public static void main(String[] args) {
Mythread m1 = new Mythread("A ");
Mythread m2 = new Mythread("B ");
Mythread m3 = new Mythread("C ");
m1.start();
m2.start();
m3.start();
}
}
2. implement Runnable 接口: Can use shared variables: 代理设计模式
class Mythread2 implements Runnable {
int ticket = 5;
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.currentThread().sleep(500);
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + ticket--);
}
} catch (Exception e) {
System.out.println(Thread.currentThread().getName() + "被中断了");
return;
}
}
}
}
public class Drunnable extends Thread {
public static void main(String[] args) {
Mythread2 mt = new Mythread2();
Thread m1 = new Thread(mt, "AA ");
Thread m2 = new Thread(mt, "BB ");
Thread m3 = new Thread(mt, "CC ");
m1.start();
m2.start();
m3.start();
try {
Thread.currentThread().sleep(1000); // main thread sleep
} catch (Exception e) {
}
System.out.println("主线程对各线程发出中断请求");
m1.interrupt();
m2.interrupt();
m3.interrupt();
}
}
----java output----
BB 5
CC 3
AA 4
主线程对各线程发出中断请求
BB 被中断了
AA 被中断了
CC 2
CC 被中断了
===线程的同步
没有评论:
发表评论