课堂代码
public class Demo01 extends Thread {
public Demo01() {
}
public Demo01(String name) {
super(name);
}
public void run() {
System.out.println("这是一个新的线程,自己实现的");
System.out.println("名字:" + Thread.currentThread().getName());
}
}
public class TestDemo01 {
public TestDemo01() {
}
public static void main(String[] args) {
Demo01 demo01 = new Demo01("1");
Demo01 demo02 = new Demo01("2");
Demo01 demo03 = new Demo01("3");
Demo01 demo04 = new Demo01("4");
demo01.setPriority(1);
demo02.setPriority(3);
demo03.setPriority(7);
demo04.setPriority(10);
demo01.start();
demo02.start();
demo03.start();
demo04.start();
}
}
public class Demo02 implements Runnable {
public Demo02() {
}
public void run() {
System.out.println("新线程,实现接口的方式");
}
}
public class TestDemo02 {
public TestDemo02() {
}
public static void main(String[] args) {
Demo02 demo02 = new Demo02();
Thread thread = new Thread(demo02);
thread.start();
}
}
public class DamemonThread implements Runnable {
public DamemonThread() {
}
public void run() {
System.out.println("进入守护线程" + Thread.currentThread().getName());
System.out.println("守护线程开工了.....");
this.writeToFile();
System.out.println("退出守护线程" + Thread.currentThread().getName());
}
public void writeToFile() {
for(int count = 0; count < 999; ++count) {
System.out.println("守护线程" + Thread.currentThread().getName() + count);
}
}
}
public class TestDemo03 {
public TestDemo03() {
}
public static void main(String[] args) throws InterruptedException {
System.out.println("进入主线程" + Thread.currentThread().getName());
DamemonThread damemonThread = new DamemonThread();
Thread thread = new Thread(damemonThread);
thread.setDaemon(true);
thread.start();
Thread.sleep(500L);
System.out.println("你好,世界");
System.out.println("退出主线程" + Thread.currentThread().getName());
}
}
public class Demo04 {
public Demo04() {
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + "卖出1张票,还剩:" + --TickerContent.count + "张");
}
};
(new Thread(r, "1")).start();
(new Thread(r, "2")).start();
(new Thread(r, "3")).start();
(new Thread(r, "4")).start();
(new Thread(r, "5")).start();
(new Thread(r, "6")).start();
}
}
public class TickerContent {
public static int count = 50;
public TickerContent() {
}
}