package demo01;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 8:32
*/
public class Demo01 extends Thread{
public Demo01(){
}
public Demo01(String name){
super(name); //修改线程的名字
}
@Override
public void run() {
System.out.println("这是一个新的线程,自己实现的");
System.out.println("名字:"+Thread.currentThread().getName()); //打印线程的名字
}
}
TextDemo01
package demo01;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 8:34
*/
public class TextDemo01 {
public static void main(String[] args) {
// Demo01 demo01 = new Demo01("线程1");
// demo01.start();
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(8);
demo04.setPriority(10);
demo01.start();
demo02.start();
demo03.start();
demo04.start();
}
}
Demo02实现接口方式
package demo02;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 8:41
*/
public class Demo02 implements Runnable {
@Override
public void run() {
System.out.println("新线程,实现接口的方式");
}
}
/*
1.实现接口
2.复写run方法
3.创建线程测试
*/
TextDemo02
package demo02;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 8:42
*/
public class TextDemo02 {
public static void main(String[] args) {
Demo02 demo02 = new Demo02();
Thread thread = new Thread(demo02);
thread.start();
}
}
Demo03守护线程及休眠
package demo01.demo03;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 9:26
*/
public class Demo03 {
public static void main(String[] args) throws InterruptedException {
System.out.println("进入守护线程"+Thread.currentThread().getName());
DaemonThread daemonThread = new DaemonThread();
Thread thread = new Thread(daemonThread);
thread.setDaemon(true);
thread.start();
Thread.sleep(500); //线程休眠500毫秒
System.out.println("hello");
System.out.println("退出主线程"+Thread.currentThread().getName());
}
}
s DaemonThread
package demo01.demo03;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 9:27
*/
public class DaemonThread implements Runnable{
@Override
public void run() {
System.out.println("进入守护线程"+Thread.currentThread().getName());
System.out.println("守护线程开工了...");
writeToFile();
System.out.println("退出守护线程"+Thread.currentThread().getName());
}
private void writeToFile() {
int count = 0 ;
while (count <999){
System.out.println("守护线程"+ Thread.currentThread().getName());
count++;
}
}
}
Demo04代码加锁
package demo04;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 10:04
*/
public class Demo04 {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (this){ //代码加锁
System.out.println(
Thread.currentThread().getName()+"卖出一张票,还剩:"+(--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();
new Thread(r,"7").start();
new Thread(r,"8").start();
}
}
package demo04;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 10:04
*/
public class TickerContent {
public static int count = 50 ;
}