如何编写一个线程类
package Chapter21_Concurrence;
public class Excersize1 implements Runnable{
private static int count = 3;
public Excersize1() {
System.out.println("Start the thread");
}
@Override
public void run() {
while(count -- >0) {
System.out.println("output"+count);
}
}
}
- 开启一个线程调用run方法
@Test
public void testEx1() {
Excersize1 ex1 = new Excersize1();
Thread threadA = new Thread(ex1);
threadA.start();
}
输出结果
Start the thread
output 2
output 1
output 0
- run方法未同步时开启两个线程调用同一个run方法
@Test
public void testEx1NonSychronized() {
Excersize1 ex1 = new Excersize1();
Thread threadA = new Thread(ex1);
Thread threadB = new Thread(ex1);
threadA.start();
threadB.start();
}
输出结果
Start the thread
output 1
output 1
output 0
- 当在run方法上添加synchronized关键字时的输出结果
@Override
public synchronized void run() {
while(count -- >0) {
System.out.println("output "+count);
}
}
输出结果
Start the thread
output 2
output 1
output 0
调用Thread.getName()获取线程的名称
@Test
public void testEx1ThreadName() {
Excersize1 ex1 = new Excersize1();
Thread threadA = new Thread(ex1);
Thread threadB = new Thread(ex1);
threadA.start();
threadB.start();
System.out.println("Name of Thread A : "+threadA.getName());
System.out.println("Name of Thread B : "+threadB.getName());
}
输出
Start the thread
Name of Thread A : Thread-0
Name of Thread B : Thread-1
output 2
output 1
output 0
- 调用Thread.getPriority()方法获取线程的优先级,当我们不设置线程的优先级时,默认使用的是优先级是5,最大优先级是10
@Test
public void testEx1ThreadPriority() {
Excersize1 ex1 = new Excersize1();
Thread threadA = new Thread(ex1);
Thread threadB = new Thread(ex1);
threadA.start();
threadB.start();
System.out.println("Priority of Thread A : "+threadA.getPriority());
System.out.println("Priority of Thread A : "+threadB.getPriority());
}
输出结果
Start the thread
Priority of Thread A : 5
Priority of Thread A : 5
output 2
output 1
output 0