Example usage for java.lang Thread currentThread

List of usage examples for java.lang Thread currentThread

Introduction

In this page you can find the example usage for java.lang Thread currentThread.

Prototype

@HotSpotIntrinsicCandidate
public static native Thread currentThread();

Source Link

Document

Returns a reference to the currently executing thread object.

Usage

From source file:Main.java

/**
 * //  ww  w  .  j ava  2  s  .  c  om
 * "waitTimeBool" wait for the given time.
 * 
 * @param time
 * @throws InterruptedException when interrupted
 */
public static void waitTimeExcept(long time) throws InterruptedException {
    synchronized (Thread.currentThread()) {
        Thread.currentThread().wait(time);
    }
}

From source file:Main.java

/**
 * Returns true if the current executing thread is the main Android app thread, false otherwise.
 */// w  w w . ja  va 2s . c  o  m
public static boolean isOnMainThread() {
    return Thread.currentThread().getId() == MainThreadId;
}

From source file:Main.java

public static boolean isMainThread() {
    return Looper.getMainLooper().getThread() == Thread.currentThread();
}

From source file:Main.java

public static InputStream getResourceAsStream(String name, Class clazz) {
    ClassLoader loader;/*from w  ww . j a v a 2s.  co  m*/
    InputStream retval = null;

    // https://issues.jboss.org/browse/JGRP-1762: load the classloader from the defining class first
    if (clazz != null) {
        try {
            loader = clazz.getClassLoader();
            if (loader != null) {
                retval = loader.getResourceAsStream(name);
                if (retval != null)
                    return retval;
            }
        } catch (Throwable t) {
        }
    }

    try {
        loader = Thread.currentThread().getContextClassLoader();
        if (loader != null) {
            retval = loader.getResourceAsStream(name);
            if (retval != null)
                return retval;
        }
    } catch (Throwable t) {
    }

    try {
        loader = ClassLoader.getSystemClassLoader();
        if (loader != null) {
            return loader.getResourceAsStream(name);
        }
    } catch (Throwable t) {
    }

    return retval;
}

From source file:Main.java

public static void call() {
    int counter = 0;
    Integer counterObject = threadLocal.get();

    if (counterObject == null) {
        counter = 1;/*from  w  w w. j  a va 2  s .c o m*/
    } else {
        counter = counterObject.intValue();
        counter++;
    }
    threadLocal.set(counter);
    String threadName = Thread.currentThread().getName();
    System.out.println("Call  counter for " + threadName + "  = " + counter);
}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters.//from www  .j ava  2 s  . c  om
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}

From source file:Main.java

public static final void sleep(long millisec) {
    try {/*  www  .  j  a  v a  2s.c o  m*/
        Thread.sleep(millisec);
    } catch (InterruptedException ignore) {
        Thread.currentThread().interrupt();
    }
}

From source file:com.mycompany.match.gender.app.FirstNamesListModel.java

static HashMap<String, String> getNames() throws IOException {
    InputStream in = Thread.currentThread().getClass().getResourceAsStream("/data/malenames.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    Iterable<CSVRecord> records = readCsv(reader);
    for (CSVRecord record : records) {
        if (record.getRecordNumber() >= 0) {
            // Here true represents male
            String key = record.get(0).toLowerCase();
            GenderNamesList.put(key, "male");
        }/*w  w w.ja  v a  2s .c om*/
    }
    in = Thread.currentThread().getClass().getResourceAsStream("/data/femalenames.txt");
    reader = new BufferedReader(new InputStreamReader(in));
    records = readCsv(reader);
    for (CSVRecord record : records) {
        if (record.getRecordNumber() >= 0) {
            // Here false represents female
            String key = record.get(0).toLowerCase();
            if (!GenderNamesList.containsKey(key)) {
                GenderNamesList.put(key, "female");
            } else {
                GenderNamesList.put(key, "either");
            }
        }
    }
    return GenderNamesList;
}

From source file:Main.java

public static void sleepMillis(int milliseconds) {
    try {//from  ww  w .j  a  v a  2 s.  c om
        Thread.sleep(milliseconds);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted sleeping", e);
    }
}

From source file:Main.java

/**
 * Execute the given runnable code dedicated to Swing using the Event Dispatcher Thread (EDT)
 * And waits for completion//w  w w . j a  v a2s .  c o m
 * @param runnable runnable code dedicated to Swing
 * @throws IllegalStateException if any exception occurs while the given runnable code executes using EDT
 */
public static void invokeAndWaitEDT(final Runnable runnable) throws IllegalStateException {
    if (isEDT()) {
        // current Thread is EDT, simply execute runnable:
        runnable.run();
    } else {
        // If the current thread is interrupted, then use invoke later EDT (i.e. do not wait):
        if (Thread.currentThread().isInterrupted()) {
            invokeLaterEDT(runnable);
        } else {
            try {
                // Using invokeAndWait to be in sync with the calling thread:
                SwingUtilities.invokeAndWait(runnable);

            } catch (InterruptedException ie) {
                // propagate the exception because it should never happen:
                throw new IllegalStateException(
                        "SwingUtils.invokeAndWaitEDT : interrupted while running " + runnable, ie);
            } catch (InvocationTargetException ite) {
                // propagate the internal exception :
                throw new IllegalStateException(
                        "SwingUtils.invokeAndWaitEDT : an exception occured while running " + runnable,
                        ite.getCause());
            }
        }
    }
}