📄 mutlithreaddemo5.java
字号:
// 例4.2.5 MutliThreadDemo5.java
class NewThread extends Thread
{
private int count;
private boolean isPass = true; // 定义一个标志,用来终止循环
NewThread( String name )
{
super(name);
}
public void run()
{
while(isPass) // isPass为假时将中止循环,否则count不断的加1
{
count++;
}
}
public int result() // 返回count的值
{
return count;
}
public void stopThread() // 中止线程
{
isPass = false;
}
}
class MutliThreadDemo5
{
public static void main( String[] args)
{
NewThread t1 = new NewThread("Thread 1");
NewThread t2 = new NewThread("Thread 2");
t1.setPriority(Thread.NORM_PRIORITY-3); //设置优先级为2
t2.setPriority(Thread.NORM_PRIORITY+3); //设置优先级为8
t1.start(); // 启动线程t1
t2.start(); // 启动线程t2
try
{
Thread.sleep(500); // 主线程睡眠500毫秒
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
System.out.println("Thread 1:Priority is "+t1.getPriority()
+" Result of Count is: "+t1.result());
System.out.println("Thread 2:Priority is "+t2.getPriority()
+" Result of Count is: "+t2.result());
t1.setPriority(Thread.MAX_PRIORITY); //重新设置t1的优先级为最大
try{
Thread.sleep(500); // 主线程睡眠500毫秒
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
t1.stopThread();
t2.stopThread();
System.out.println("After the priority of Thread 1 is changed: ");
System.out.println("Thread 1:Priority is "+t1.getPriority()
+" Result of Count is: "+t1.result());
System.out.println("Thread 2:Priority is "+t2.getPriority()
+" Result of Count is: "+t2.result());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -