易网时代-编程资源站
Welcome
微信登录
首页
/
操作系统
/
Linux
/
JAVA线程的应用实例
JAVA线程的应用实例(运用2种中断线程方式,基于实现进度条为例)
Java内置了对多线程的支持,那些在其他语言中必须由手工完成的工作,现在都可以由Java自动处理。我们进入多线程就像进入了一个全新的领域,因为它的编程思想打破了传统,传统的程序代码一般都是从上到下一条一条的执行的,而多线程允许多个代码块并行执行。所以多线程编程模式可以更好的模拟现实世界的应用。可以说,java对多线程的内置支持是对传统的计算机编程领域的一次突破贡献。我们不应该去抵制它,而是更好的去熟悉和利用它。
C++没有对多线程编程提供内置支持,于是就必须依赖于操作系统来处理多线程任务。这就意味着创建、启动、同步和结束线程都必须通过对操作系统的多次调用来实现。因此C++中的多线程代码是不可移植的。这也使得C++编程中的多线程没有得以广泛应用。
package
com.han;
import
java.awt.*;
import
javax.swing.*;
/**
* 内部类与匿名内部类的分别使用,并且分别运用了interrupt()方法和在run()中使用无限循环,然后用一个布尔什标记去控制循环的停止
* @author HAN
*
*/
@SuppressWarnings
(
"serial"
)
public
class
Thread_interrupt
extends
JFrame{
static
Thread thread;
JProgressBar progressBar;
public
Thread_interrupt(){
progressBar=
new
JProgressBar();
progressBar.setStringPainted(
true
);
Container container=getContentPane();
container.add(progressBar, BorderLayout.NORTH);
//在不指定布局管理器的情况下,默认使用BorderLayout。 若不使用布局管理器,需明确说明setLayout(new BorderLayout())
this
.pack();
this
.setVisible(
true
);
this
.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this
.creatThread();
thread.start();
//thread_instance.setContinue(false); //另一种中断线程方式
thread.interrupt();
}
class
Thread_instance
implements
Runnable{
boolean
isContinue=
true
;
public
void
setContinue(
boolean
b){
this
.isContinue=b;
}
@Override
public
void
run() {
// TODO Auto-generated method stub
int
count=
0
;
while
(
true
){
progressBar.setValue(++count);
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(
"当前程序被中断"
);
break
;
}
if
(!isContinue){
break
;
}
}
System.out.println(
"here"
);
}
}
void
creatThread(){
thread=
new
Thread(
new
Thread_instance());
}
static
void
init(JFrame frame,
int
width,
int
height){
frame.setSize(width,height);
}
public
static
void
main (String[] args){
init(
new
Thread_interrupt(),
100
,
100
);
}
}
/*@SuppressWarnings("serial")
public class Thread_interrupt extends JFrame{
Thread thread;
JProgressBar progressBar;
boolean isContinue=true;
public Thread_interrupt(){
progressBar=new JProgressBar();
progressBar.setStringPainted(true);
Container container=getContentPane();
container.add(progressBar);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
thread=new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
int count=0;
while(true){
progressBar.setValue(++count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("当前程序被中断");
break;
}
if(!isContinue){
break;
}
}
System.out.println("here");
}
});
thread.start();
// thread.interrupt();
setContinue(false);
}
*//**
* @param b true=continue to execute run();
* false=stop to execute run()
*//*
private void setContinue(boolean b) {
// TODO Auto-generated method stub
this.isContinue=b;
}
public static void main (String[] args){
new Thread_interrupt();
}
}
*/
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图