以下例子包含:创建类的唯一实例、锁定资源、定时动作。
具体运行一下就知道了,要真正学会多线程编程,必须看书。在这里听别人讲几句,只能算是了解一下而已。
Test.java文件内容如下:
-----------------------------------------------------------------
class Do_something{
public static void writeString(int i){
System.out.println(i);
}
}class TestThread extends Thread{
private static TestThread test;
int i=1;
//私有构造函数
private TestThread(){}
//取得TestThread的唯一实例
public static TestThread getInstance(){
if(test==null){
test=new TestThread();
return test;
}
else return test;
}
private void add(){
i++;
}
public void run(){
while(true){
//以下是在锁定test对象的情况下运行代码
synchronized(test){
add();
if(i>100) break;//只循环一百次,之后结束线程
if(i%10==0) Do_something.writeString(i);//输出被十整除者
try{
Thread.sleep(250);//让线程暂停250毫秒,不必使用timer
}catch(java.lang.InterruptedException e){}
}
}
}
}
public class Test{
public static void main(String []args){
TestThread.getInstance().start();
}
}
具体运行一下就知道了,要真正学会多线程编程,必须看书。在这里听别人讲几句,只能算是了解一下而已。
Test.java文件内容如下:
-----------------------------------------------------------------
class Do_something{
public static void writeString(int i){
System.out.println(i);
}
}class TestThread extends Thread{
private static TestThread test;
int i=1;
//私有构造函数
private TestThread(){}
//取得TestThread的唯一实例
public static TestThread getInstance(){
if(test==null){
test=new TestThread();
return test;
}
else return test;
}
private void add(){
i++;
}
public void run(){
while(true){
//以下是在锁定test对象的情况下运行代码
synchronized(test){
add();
if(i>100) break;//只循环一百次,之后结束线程
if(i%10==0) Do_something.writeString(i);//输出被十整除者
try{
Thread.sleep(250);//让线程暂停250毫秒,不必使用timer
}catch(java.lang.InterruptedException e){}
}
}
}
}
public class Test{
public static void main(String []args){
TestThread.getInstance().start();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货