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("這是一個新的線程犬辰,自己實現(xiàn)的");
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");
//線程的優(yōu)先級
demo01.setPriority(1);
demo02.setPriority(3);
demo03.setPriority(8);
demo04.setPriority(10);
demo01.start();
demo02.start();
demo03.start();
demo04.start();
}
}
Demo02實現(xiàn)接口方式
package demo02;
/**
* @qvthor liuwenzheng
* @date 2021/5/19 8:41
*/
public class Demo02 implements Runnable {
@Override
public void run() {
System.out.println("新線程,實現(xiàn)接口的方式");
}
}
/*
1.實現(xiàn)接口
2.復寫run方法
3.創(chuàng)建線程測試
*/
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 ;
}