用Thread的子类创建线程
package work05;
//兔子 ---多线程
public class Robot extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("兔子跑了" + i + "步!");
}
}
}
package work05;
//乌龟---多线程
public class Torties extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("乌龟跑了" + i + "步!");
}
}
}
package work05;
public class Demo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Robot r = new Robot();
r.start();// 在主运行线程上又新产生一个线程
Torties t = new Torties();
t.start();
for (int i = 1; i <= 10; i++) {
System.out.println("我跑了" + i + "步!");
}
}
}
用Runnable接口方式创建线程
package work05;
public class Robot1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 10; i++) {
System.out.println("兔子跑了" + i + "步!");
}
}
}
package work05;
public class Torties1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 10; i++) {
System.out.println("乌龟跑了" + i + "步!");
}
}
}
package work05;
public class Demo0101 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Robot1 r1 = new Robot1();
Thread r2 = new Thread(r1);
r2.start();
Torties1 t1 = new Torties1();
Thread t2 = new Thread(t1);
t2.start();
}
}
简单的12306售票
package work05;
public class Demo12306 implements Runnable {
int num = 10;
@Override
public void run() {
// TODO Auto-generated method stub
int sum = 0;
String list = "";
while (true) {
if (num <= 0) {
break;
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 同步锁
synchronized (this) {
if (num <= 0) {
break;
}
System.out.println(Thread.currentThread().getName() + "抢到了"
+ num);
list = list + num + ",";
num--;
sum++;
System.out.println(Thread.currentThread().getName() + "抢到了"
+ list);
System.out.println(Thread.currentThread().getName() + "共抢到了"
+ sum+"张票");
}
}
}
}
package work05;
public class Demo123 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo12306 d = new Demo12306();
Thread d1 = new Thread(d, "小明");
Thread d2 = new Thread(d, "小红");
Thread d3 = new Thread(d, "小华");
d1.start();
d2.start();
d3.start();
}
}