Thread类
创建多线程
package Threading;
public class MyThread extends Thread{
@Override
public void run() {
for(int i =0;i<100;i++){
System.out.println(i);
}
}
}
package Threading;
public class test {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
设置和获取线程名称
package Threading;
public class MyThread extends Thread{
public MyThread() {
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for(int i =0;i<100;i++){
System.out.println(getName()+":"+i);
}
}
}
package Threading;
public class test {
public static void main(String[] args) {
MyThread t1 = new MyThread("高铁");
MyThread t2 = new MyThread("飞机");
System.out.println(Thread.currentThread().getName());
t1.start();
t2.start();
}
}
查看和设置线程优先级
package Threading;
public class test {
public static void main(String[] args) {
MyThread t1 = new MyThread("高铁");
MyThread t2 = new MyThread("飞机");
MyThread t3 = new MyThread("汽车");
t1.setPriority(5);
t2.setPriority(10);
t3.setPriority(1);
t1.start();
t2.start();
t3.start();
}
}
sleep、join、daemon
package Threading;
public class MyThread extends Thread{
public MyThread() {
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for(int i =0;i<100;i++){
System.out.println(getName()+":"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package Threading;
public class test {
public static void main(String[] args) {
MyThread t1 = new MyThread("刘备");
MyThread t2 = new MyThread("孙权");
MyThread t3 = new MyThread("曹操");
t1.start();
t2.start();
t3.start();
}
}
package Threading;
public class test {
public static void main(String[] args) {
MyThread t1 = new MyThread("康熙");
MyThread t2 = new MyThread("四阿哥");
MyThread t3 = new MyThread("八阿哥");
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
t3.start();
}
}
package Threading;
public class test {
public static void main(String[] args) {
MyThread t1 = new MyThread("关羽");
MyThread t2 = new MyThread("张飞");
Thread.currentThread().setName("刘备");
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}