1.创建线程
package thread1;
//创建线程
public class Thread1 extends Thread {
public static void main(String[] args) {
Thread1 t =new Thread1();
t.start(); //这里需要调用start方法才能调用线程,不能直接调用run。
for (int i = 0 ; i<100; i++) {
System.out.println("main:"+i);
}
}
@Override
public void run() {
for (int i = 0 ; i<100; i++) {
System.out.println("自定义线程:"+i);
}
}
}
package thread1;
//测试两个类对象抢CPU的现象
class TalkThread extends Thread{
@Override
public void run() {
while(true) {
System.out.println("Hi,nice to meet you!");
}
}
}
class VideoThread extends Thread{
@Override
public void run() {
while(true){
System.out.println("Please open the video");
}
}
}
public class Thread2 {
public static void main(String[] args) {
TalkThread a = new TalkThread();
a.start();
VideoThread b = new VideoThread();
b.start();
}
}
package thread1;
//测试两个类对象抢CPU的现象
class TalkThread extends Thread{
@Override
public void run() {
while(true) {
System.out.println("Hi,nice to meet you!");
}
}
}
class VideoThread extends Thread{
@Override
public void run() {
while(true){
System.out.println("Please open the video");
}
}
}
public class Thread2 {
public static void main(String[] args) {
TalkThread a = new TalkThread();
a.start();
VideoThread b = new VideoThread();
b.start();
}
}
package thread1;
//sleep¤tThread方法,返回当前执行线程的对象
public class Thread4 extends Thread {
public Thread4(String name) {
super(name);
}
@Override
public void run() {
System.out.println("this"+this);
System.out.println("当前对象"+Thread.currentThread()); //那个线程执行了此方法,就返回该线程的对象
for (int i = 0 ; i<100; i++) {
System.out.println(this.getName()+":"+i);
try {
Thread.sleep(50); //设置线程休眠的时间(毫秒)
}catch(InterruptedException e) {
e.printStackTrace(); //这里不能抛出异常,只能捕获异常。因为Thread类的run方法没有抛出异常类型,所以子类不能抛出异常类型
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread4 t = new Thread4("liwenkai");
// t.sleep(100); //无论调用什么对象,都是主线程在睡眠,sleep方法是静态方法
// t.setName("lisen"); //这里也可以给线程命名。
t.start();
Thread mainThread = Thread.currentThread(); //返回当前CPU在执行的线程对象
System.out.println("主线程的名称:"+mainThread);
}
}
package thread1;
//getPriority&setPriority
public class Thread6 extends Thread {
public Thread6(String name) {
super(name);
}
@Override
public void run() {
System.out.println("this"+this);
System.out.println("当前对象"+Thread.currentThread()); //那个线程执行了此方法,就返回该线程的对象
for (int i = 0 ; i<10; i++) {
System.out.println(this.getName()+":"+i);
try {
Thread.sleep(50); //设置线程休眠的时间(毫秒)
}catch(InterruptedException e) {
e.printStackTrace(); //这里不能抛出异常,只能捕获异常。因为Thread类的run方法没有抛出异常类型,所以子类不能抛出异常类型
}
}
}
public static void main(String[] args) {
Thread6 t = new Thread6("liwenkai");
t.setPriority(8); //设置优先级优先级的数值越大,优先级越高,优先级的范围1-10
System.out.println("自定义的线程优先级"+t.getPriority()); //线程的默认优先级是5。
System.out.println("主线程的优先级"+Thread.currentThread().getPriority()); //线程的默认优先级是5
t.setName("lisen");
System.out.println(t.getName());
t.start();
for(int i =0; i<10;i++) {
System.out.println(Thread.currentThread().getName()+":"+i); //获取主线程的名称
}
}
}