我正在使用Java修改MultiThreading。我记得如果你没有使用Synchronized(在对象或实例上)方法,那么Method可以由多个线程并行执行。这就是一般情况。 以下是我写的代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.File;
class FileIn
{
File f;
BufferedWriter br;
public FileIn(String path) throws IOException
{
f = new File(path);
br = new BufferedWriter(new FileWriter(f));
}
public void write(String a) throws IOException
{
br.write(a);
br.newLine();
System.out.println(a);
}
public void close() throws IOException
{
br.close();
}
}
class ThreadWriter extends Thread
{
private FileIn f;
private String tname;
public ThreadWriter(FileIn f,String name)
{
this.f=f;
this.tname=name;
}
public void run()
{
try{
for(int i =1;i<=20;i++)
{
f.write("This is Line "+i+" of "+tname);
Thread.sleep(500);
}
}
catch(IOException e)
{
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
class Three
{
public static void main(String a[])
{
FileIn f;
Thread[] t = new Thread[4];
try{
f = new FileIn("F:/files.txt");
t[0]=new ThreadWriter(f,"Thread 1");
t[1]=new ThreadWriter(f,"Thread 2");
t[2]=new ThreadWriter(f,"Thread 3");
t[3]=new ThreadWriter(f,"Thread 4");
t[0].run();
t[1].run();
t[2].run();
t[3].run();
f.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
输出非常有序,不同的运行没有任何区别。如果我按顺序写在主页中,它就像是一样。
This is Line 1 of Thread 1
This is Line 2 of Thread 1
This is Line 3 of Thread 1
This is Line 4 of Thread 1
This is Line 5 of Thread 1
This is Line 1 of Thread 2
This is Line 2 of Thread 2
This is Line 3 of Thread 2
This is Line 4 of Thread 2
This is Line 5 of Thread 2
This is Line 1 of Thread 3
This is Line 2 of Thread 3
This is Line 3 of Thread 3
This is Line 4 of Thread 3
This is Line 5 of Thread 3
This is Line 1 of Thread 4
This is Line 2 of Thread 4
This is Line 3 of Thread 4
This is Line 4 of Thread 4
This is Line 5 of Thread 4
我认为这可能是由于某些特定于CPU但程序在这里发生的: http://www.tutorialspoint.com/java/java_multithreading.htm 按原样运行 - 线程在没有同步的情况下相互重叠。
我认为BufferedWriter可能已经是ThreadSafe,这可能允许它做这样的事情。(即使线程不能锁定BufferdWriter,FileIn应该),但显然它不是。
那为什么这不像线程不安全方法?
答案 0 :(得分:5)
您没有启动任何新线程,而是在原始主线程上执行Thread
对象的run方法。您需要致电thread.start()
而不是thread.run()
。
如果你确实解决了这个问题,如果每个线程的任务很短,你仍然可以得到相同的输出。确保要做的工作足够长,以便查看您想要的行为。