Navigation of this series of articles
Java multithreading (1)-method join
Java multithreading (2)-EDT in Swing (event distribution thread)
In-depth introduction to multithreading (3)-Future asynchronous mode and its implementation in the JDK1.5Concurrent package
Introduction to multithreading (4) some ideas on the problem of CachedThreadPool OutOfMemoryError
Deep introduction to multithreading (5) use the parallel package thread pool as an example to describe the design requirements and usage of the thread pool
Deep introduction to multithreading (6) Design and implementation of parallel package Thread Pool
This article mainly solves the following problems:
How to make its Swing program run only one instance?
Aside from Swing, our program starts a process to execute through the java command line. This problem is to ensure the uniqueness of this process. Of course, if we can access the system interface, obtain the process information to determine whether the existing process is running. Isn't it solved? But how to access the system interface? How can we ensure that they are OK on different platforms? My idea is to use File locks. Of course, I believe there must be better methods. I hope readers can point it out.
The file lock is proposed by JDK1.4 NIO. You can obtain the file lock when reading a file. The lock should be maintained by the system, and the JVM should be the called system file lock mechanism. The example is as follows:
package concurrentstudy;</p><p>import java.io.FileNotFoundException;<br />import java.io.IOException;<br />import java.io.RandomAccessFile;<br />import java.nio.channels.FileChannel;<br />import java.nio.channels.FileLock;</p><p>/**<br /> * @author vma<br /> */<br />public class temp1 {<br />public static void main(String args[]) throws FileNotFoundException, InterruptedException, IOException {<br />RandomAccessFile r = new RandomAccessFile("d://testData.java", "rw");<br />FileChannel temp = r.getChannel();<br />FileLock fl = temp.lock();<br />System.out.println(fl.isValid());<br />Thread.sleep(100000);<br />temp.close();<br />}<br />}<br />
After the code gets the lock: if we try to edit this file, it will:
{
Function onclick ()
{
Function onclick ()
{
Function onclick ()
{
Get_larger (this)
}
}
}
} "Src =" http://p.blog.csdn.net/images/p_blog_csdn_net/hemingwang0902/EntryImages/20090916/1.JPG "alt =" deep dive into Java multithreading (2)-EDT in Swing (event distribution thread) ">
If you start a Java Main method:
Package concurrentstudy; </p> <p> import java. io. fileNotFoundException; <br/> import java. io. IOException; <br/> import java. io. randomAccessFile; <br/> import java. nio. channels. fileChannel; <br/> import java. nio. channels. fileLock; </p> <p> public class Temp2 {<br/> public static void main (String args []) throws FileNotFoundException, InterruptedException, IOException {<br/> RandomAccessFile r = new RandomAccessFile ("d: // testData. java "," rw "); <br/> FileChannel temp = r. getChannel (); <br/> FileLock fl = temp. tryLock (); <br/> System. out. println (fl = null); <br/> temp. close (); <br/>}< br/>}
The returned result is true, that is, the file lock is not obtained.
This is my Solution to the Problem of process uniqueness. By locking the file, it cannot be started without locking the file when it is started again.
Speaking of this, it seems that EDT in Swing has nothing to do with today. For Swing programs, the Main method is generally like this:
Public static void main (String [] args) {<br/> try {<br/> UIManager. setLookAndFeel (UIManager. getCrossPlatformLookAndFeelClassName (); <br/>}catch (Exception e) {<br/>}< br/> // Create the top-level container and add contents to it. <br/> JFrame = new JFrame ("SwingApplication"); <br/> SwingApplication app = new SwingApplication (); <br/> Component contents = app. createComponents (); <br/> frame. getContentPane (). add (contents, BorderLayout. CENTER); <br/> frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); <br/> frame. pack (); <br/> frame. setVisible (true );
After Jframe is started, the Main thread exits. Where can I write the logic of obtaining the file lock and holding the lock? Some people will say that the event distribution thread EDT, is it true?
Since I have not worked on Swing projects, I have only worked on small financial management software for my personal use, and I have not fully understood EDT. In any case, add that logic to EDT first,
How to add it? Use SwingUtilities.
static void invokeAndWait(Runnable doRun)
Causes doRun.run() to be executed synchronously on the AWT event dispatching thread.
static void invokeLater(Runnable doRun)
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread.
After adding it, how does the interface not respond?
The Code is as follows:
package concurrentstudy;</p><p>import java.awt.BorderLayout;<br />import java.awt.Component;<br />import java.awt.GridLayout;<br />import java.awt.event.ActionEvent;<br />import java.awt.event.ActionListener;<br />import java.awt.event.KeyEvent;<br />import java.io.FileNotFoundException;<br />import java.io.IOException;<br />import java.io.RandomAccessFile;<br />import java.lang.reflect.InvocationTargetException;<br />import java.nio.channels.FileChannel;<br />import java.nio.channels.FileLock;<br />import java.util.logging.Level;<br />import java.util.logging.Logger;</p><p>import javax.swing.BorderFactory;<br />import javax.swing.JButton;<br />import javax.swing.JFrame;<br />import javax.swing.JLabel;<br />import javax.swing.JPanel;<br />import javax.swing.SwingUtilities;<br />import javax.swing.UIManager;</p><p>public class SwingApplication {<br />private static String labelPrefix = "Number of button clicks: ";</p><p>private int numClicks = 0;</p><p>public Component createComponents() {<br />final JLabel label = new JLabel(labelPrefix + "0");<br />JButton button = new JButton("I'm a Swing button!");<br />button.setMnemonic(KeyEvent.VK_I);<br />button.addActionListener(new ActionListener() {<br />public void actionPerformed(ActionEvent e) {<br />numClicks++;<br />label.setText(labelPrefix + numClicks);<br />}<br />});<br />label.setLabelFor(button);<br />/*<br /> * An easy way to put space between a top-level container and its<br /> * contents is to put the contents in a JPanel that has an "empty"<br /> * border.<br /> */<br />JPanel pane = new JPanel();<br />pane.setBorder(BorderFactory.createEmptyBorder(30, // top<br />30, // left<br />10, // bottom<br />30) // right<br />);<br />pane.setLayout(new GridLayout(0, 1));<br />pane.add(button);<br />pane.add(label);<br />return pane;<br />}</p><p>public static void main(String[] args) throws InterruptedException {<br />try {<br />UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());<br />} catch (Exception e) {<br />}<br />// Create the top-level container and add contents to it.<br />JFrame frame = new JFrame("SwingApplication");<br />SwingApplication app = new SwingApplication();<br />Component contents = app.createComponents();<br />frame.getContentPane().add(contents, BorderLayout.CENTER);<br />frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />frame.pack();<br />frame.setVisible(true);<br />try {<br />SwingUtilities.invokeAndWait(new getFileLock());<br />} catch (InvocationTargetException ex) {<br />ex.printStackTrace();<br />}<br />}<br />}</p><p>class getFileLock implements Runnable {<br />public void run() {<br />try {<br />RandomAccessFile r = null;<br />try {<br />r = new RandomAccessFile("d://testData.java", "rw");<br />} catch (FileNotFoundException ex) {<br />ex.printStackTrace();<br />}<br />FileChannel temp = r.getChannel();<br />FileLock fl = null;<br />try {<br />fl = temp.lock();<br />} catch (IOException ex) {<br />Logger.getLogger(getFileLock.class.getName()).log(Level.SEVERE, null, ex);<br />}<br />System.out.println(fl.isValid());<br />try {<br />Thread.sleep(Integer.MAX_VALUE);<br />} catch (InterruptedException ex) {<br />ex.printStackTrace();<br />}<br />temp.close();<br />} catch (IOException ex) {<br />ex.printStackTrace();<br />}<br />}<br />}<br />
Click a breakpoint to see what is going on. The breakpoint is here Thread. sleep (Integer. MAX_VALUE); Check that the Thread is paused. See the picture:
{
Function onclick ()
{
Function onclick ()
{
Function onclick ()
{
Get_larger (this)
}
}
}
} "Src =" http://p.blog.csdn.net/images/p_blog_csdn_net/hemingwang0902/EntryImages/20090916/2.JPG "alt =" deep dive into Java multithreading (2)-EDT in swing (event distribution thread) ">
See it, The getfilelock we write is executed by the AWT-EventQueue-0 thread, look at the call relationship in the lower right corner, eventdispaththread start the run method, then pumpevents get the event, then get from eventqueue to invocationevent execute dispath
Dispath calls the run () method written in getfilelock. The JDK code is as follows:
public void dispatch() {<br /> if (catchExceptions) {<br /> try {<br /> runnable.run();<br /> }<br /> catch (Throwable t) {<br /> if (t instanceof Exception) {<br /> exception = (Exception) t;<br /> }<br /> throwable = t;<br /> }<br /> }<br /> else {<br /> runnable.run();<br /> }<br /> if (notifier != null) {<br /> synchronized (notifier) {<br /> notifier.notifyAll();<br /> }<br /> }<br /> }
runnable.run();How can we add getfilelock to the eventqueue? Of course it is swingutilities. invokeandwait (New getfilelock ());
Check the JDK code:
public static void invokeAndWait(Runnable runnable) throws InterruptedException, InvocationTargetException {<br /> if (EventQueue.isDispatchThread()) {<br /> throw new Error("Cannot call invokeAndWait from the event dispatcher thread");<br /> }<br /> class AWTInvocationLock {}<br /> Object lock = new AWTInvocationLock();<br /> InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), runnable, lock, true);<br /> synchronized (lock) {<br /> Toolkit.getEventQueue().postEvent(event);<br /> lock.wait();<br /> }
Toolkit. geteventqueue (). postevent (event); inserts the getfilelock we wrote into eventqueue.
Now, the reader has an idea about EDT.
1. EDT has only one thread. Although getfilelock implements the runnable interface, it calls the run method instead of the star method to start a new thread.
2. invokeandwait inserts the getfilelock you wrote into eventqueue.
3. The Swing event mechanism uses the product consumer mode. EDT constantly retrieves events (consumers) from eventqueue ). Other threads can insert events into eventqueue. For example, if you click "button", the events registered in buttion are inserted into eventqueue.
Therefore, after we insert getFileLock as an event, EDT distribution goes to bed when Thread. sleep (Integer. MAX_VALUE) is called. Other events that cannot be inserted into EventQueue, such as closing the form.
Therefore, the logic holding the lock cannot be inserted into EventQueue, but should be placed in the main thread or other threads outside.
When it comes to invokeAndWait, what are the differences between invokelater and invokeAndWait?
Difference between invokeAndWait and invokelater: Check the JDK code:
public static void invokeLater(Runnable runnable) {<br /> Toolkit.getEventQueue().postEvent(<br /> new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));<br /> }<br />public static void invokeAndWait(Runnable runnable) throws InterruptedException, InvocationTargetException {<br /> if (EventQueue.isDispatchThread()) {<br /> throw new Error("Cannot call invokeAndWait from the event dispatcher thread");<br /> }<br /> class AWTInvocationLock {}<br /> Object lock = new AWTInvocationLock();<br /> InvocationEvent event = new InvocationEvent(Toolkit.getDefaultToolkit(), runnable, lock, true);<br /> synchronized (lock) {<br /> Toolkit.getEventQueue().postEvent(event);<br /> lock.wait();<br /> }<br /> Throwable eventThrowable = event.getThrowable();<br /> if (eventThrowable != null) {<br /> throw new InvocationTargetException(eventThrowable);<br /> }<br /> }
Invokelater: When SwingUtils. invokelater is called in the main method, the event is inserted into EventQueue and the main thread is not blocked.
InvokeAndWait: When SwingUtils. invokeAndWait is called in the Main method, read the code snippet:
synchronized (lock) {
Toolkit.getEventQueue().postEvent(event);
lock.wait();
}The main thread wait () after obtaining the lock, until the event distribution thread calls notify of the lock object to wake up the main thread, otherwise the main thread will wait.
Now, I understand!
In short, the simplest way to solve our problem is in the main thread or in other threads.
The final solution is:
package concurrentstudy;</p><p>import java.awt.BorderLayout;<br />import java.awt.Component;<br />import java.awt.GridLayout;<br />import java.awt.event.ActionEvent;<br />import java.awt.event.ActionListener;<br />import java.awt.event.KeyEvent;<br />import java.io.FileNotFoundException;<br />import java.io.IOException;<br />import java.io.RandomAccessFile;<br />import java.nio.channels.FileChannel;<br />import java.nio.channels.FileLock;</p><p>import javax.swing.BorderFactory;<br />import javax.swing.JButton;<br />import javax.swing.JFrame;<br />import javax.swing.JLabel;<br />import javax.swing.JPanel;<br />import javax.swing.UIManager;</p><p>public class SwingApplication {<br />private static String labelPrefix = "Number of button clicks: ";</p><p>private int numClicks = 0;</p><p>public Component createComponents() {<br />final JLabel label = new JLabel(labelPrefix + "0");<br />JButton button = new JButton("I'm a Swing button!");<br />button.setMnemonic(KeyEvent.VK_I);<br />button.addActionListener(new ActionListener() {<br />public void actionPerformed(ActionEvent e) {<br />numClicks++;<br />label.setText(labelPrefix + numClicks);<br />}<br />});<br />label.setLabelFor(button);<br />/*<br /> * An easy way to put space between a top-level container and its<br /> * contents is to put the contents in a JPanel that has an "empty"<br /> * border.<br /> */<br />JPanel pane = new JPanel();<br />pane.setBorder(BorderFactory.createEmptyBorder(30, // top<br />30, // left<br />10, // bottom<br />30) // right<br />);<br />pane.setLayout(new GridLayout(0, 1));<br />pane.add(button);<br />pane.add(label);<br />return pane;<br />}</p><p>public static void main(String[] args) throws InterruptedException {<br />try {<br />UIManager.setLookAndFeel(UIManager<br />.getCrossPlatformLookAndFeelClassName());<br />} catch (Exception e) {<br />}<br />Thread t = new Thread(new getFileLock());<br />t.setDaemon(true);<br />t.start();<br />// Create the top-level container and add contents to it.<br />JFrame frame = new JFrame("SwingApplication");<br />SwingApplication app = new SwingApplication();<br />Component contents = app.createComponents();<br />frame.getContentPane().add(contents, BorderLayout.CENTER);<br />frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />frame.pack();<br />frame.setVisible(true);<br />}<br />}</p><p>class getFileLock implements Runnable {<br />public void run() {<br />try {<br />RandomAccessFile r = null;<br />try {<br />r = new RandomAccessFile("d://testData.java", "rw");<br />} catch (FileNotFoundException ex) {<br />ex.printStackTrace();<br />}<br />FileChannel temp = r.getChannel();<br />try {<br />FileLock fl = temp.tryLock();<br />if (fl == null)<br />System.exit(1);<br />} catch (IOException ex) {<br />ex.printStackTrace();<br />}<br />try {<br />Thread.sleep(Integer.MAX_VALUE);<br />} catch (InterruptedException ex) {<br />ex.printStackTrace();<br />}<br />temp.close();<br />} catch (IOException ex) {<br />ex.printStackTrace();<br />}<br />}<br />}<br />
Start a Daemon thread in the Main method and hold the lock. if the lock cannot be obtained, exit if (fl = null) System. exit (1 );
Of course, this is only a solution. It depends on the specific situation to give users a prompt and lock the file.
Blog Source:Http://www.cqzol.com/programming/Java/200812/198649.html