62,614
社区成员
发帖
与我相关
我的任务
分享
package test;
public class MutliThreadDemo {
public static void main(String [] args){
MutliThread m=new MutliThread();
Thread t1=new Thread(m,"window 1");
Thread t2=new Thread(m,"window 2");
Thread t3=new Thread(m,"window 3");
t1.start();
t2.start();
t3.start();
}
}
class MutliThread implements Runnable{
private int ticket=20;//所有线程一共拥有20张票
private int a;
public void run(){
while(ticket>0){
System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
}
}
}
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
public class ThreadTest {
public static void main(String [] args){
DemoThread dt=new DemoThread();
Thread t1=new Thread(dt);
Thread t2=new Thread(dt);
Thread t3=new Thread(dt);
t1.start();
t2.start();
t3.start();
}
}
class DemoThread implements Runnable{
private int num=20;//所有线程一共输出0次
private String fl = "F:\\Test.txt";
File f = new File(fl);
public void run(){
if(f.exists() && f.isFile()){
System.out.println("使用已经存在的Test.txt文件");
}else{
try{
//创建文件
f.createNewFile();
System.out.println("创建Test.txt文件");
}catch(IOException e){
System.out.println("创建Test.txt文件失败,错误信息:"+e.getMessage());
return;
}
}
while(num>0){
try {
FileOutputStream fos = new FileOutputStream(f,true);
PrintWriter pw = new PrintWriter(fos);
pw.write(num--+" ---"+Thread.currentThread().getName());//每输出一次num-1
pw.println();
pw.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
}
public class MutliThreadDemo {
public static void main(String[] args) throws IOException {
MutliThread m = new MutliThread();
Thread t1 = new Thread(m, "window 1");
Thread t2 = new Thread(m, "window 2");
Thread t3 = new Thread(m, "window 3");
t1.start();
t2.start();
t3.start();
System.in.read();
}
}
class MutliThread implements Runnable {
private AtomicInteger a = new AtomicInteger(0);
public void run() {
int num = 0;
while ((num = a.incrementAndGet()) <= 20) {
System.out.println(num + " is saled by " + Thread.currentThread().getName());
}
}
}
给一个正确的例子,可以在网上搜下Java内存模型的文章学习下