Javase Review Summary 3

Source: Internet
Author: User
Tags thread class ticket

1. Threads

Thread class:

Public final String GetName (): Returns the name of the thread

Public final void SetName (String name): Change the thread name to be the same as the parameter name

Getthreadgroup (): Returns the thread group to which the thread belongs.

Line-controlled system:

public static void sleep (Long Millis): Thread hibernation

Public final void Join (): Thread join (waits for the thread to terminate)

public static void Yeild (): Thread comity (pauses the currently executing thread object and executes other threads.) )

Public final void Setdaemon (Boolean on): Background thread

Public final void Stop (): obsolete. This method has inherent insecurity. Terminating a thread with Thread.stop will release all the monitors it has locked

public void Interrupt (): Middle break thread.

Multi-threaded implementation:

1) inherit the thread class

Steps
A: Custom class Mythread inherits the thread class.
B:mythread class inside rewrite run ()
C: Create an Object
D: Start thread

public class MyThread extends Thread {

public void Run () {
for (int x = 0; x < n × x + +) {
SYSTEM.OUT.PRINTLN (x);
}
}

}

public class Mythreaddemo {
public static void Main (string[] args) {

  Run (): Just encapsulate the code executed by the thread, the direct call is the normal method
Start (): Starts the thread first, and then the JVM calls the thread's run () method.

Illegalthreadstateexception: Illegal thread-state exception

Create two Thread objects
MyThread my1 = new MyThread ();
MyThread my2 = new MyThread ();

Start thread

My1.start ();
My2.start ();
}
}

2) Implement Runnable interface (implement interface to avoid the limitations of Java single inheritance)

Steps:
A: Custom class myrunnable Implementation Runnable interface
B: Rewrite the Run () method
C: Create an object of the Myrunnable class
D: Create the object of the thread class and pass the C-Step object as a construction parameter

public class Myrunnable implements Runnable {

public void Run () {
for (int x = 0; x < + × x + +) {
The method of the thread class cannot be used directly because of the way the interface is implemented, but it can be used indirectly
System.out.println (Thread.CurrentThread (). GetName () + ":" + x);
}
}

}

public class Myrunnabledemo {
public static void Main (string[] args) {
To create an object of the Myrunnable class
myrunnable my = new myrunnable ();

Creates an object of the thread class and passes the C-step object as a construction parameter

Thread (Runnable target, String name)
thread T1 = new Thread (My, "AA");
Thread t2 = new Thread (My, "BB");

T1.start ();
T2.start ();
}
}

Troubleshooting Thread Safety issues:

1) Synchronizing code blocks:

Synchronized (object) {
Code that needs to be synchronized;
}


Synchronization can solve the root cause of security problems on that object. The object is like the function of a lock. Multiple threads must be the same lock.

public class Sellticket implements Runnable {
Define 100 Tickets
private int tickets = 100;
To create a lock object
 Private Object obj = new Object ();


@Override
public void Run () {
while (true) {
  synchronized (obj) {
if (Tickets > 0) {
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "being sold" + (tickets--) + "Ticket");
}
}
}
}
}

2) Synchronization method: Add synchronization to the method

 Normal method (synchronization object is this)

Private synchronized void Sellticket () {

if (Tickets > 0) {
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName ()+ "being sold" + (tickets--) + "Ticket");
}
}

public void Run () {
while (true) {
if (x%2==0) {
synchronized (this) {
if (Tickets > 0) {
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName ()
+ "being sold" + (tickets--) + "Ticket");
}
}
}else {}

The lock object for a static method is: the class's bytecode file object

Private static synchronized void Sellticket () {
if (Tickets > 0) {
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName ()
+ "being sold" + (tickets--) + "Ticket");
}
}
}

public void Run () {
while (true) {
if (x%2==0) {
synchronized (sellticket.class) {//This cannot be this, because static does not have this static is loaded with the class loading, first into the memory is the class bytecode file
if (Tickets > 0) {
try {
Thread.Sleep (100);

Lock locks

void Lock (): Gets the lock. (If the lock is not available, the current thread is disabled for thread scheduling purposes, and the thread will remain dormant until the lock is acquired.) )

void Unlock (): Release lock

public class Sellticket implements Runnable {

Define Tickets
private int tickets = 100;

Defining Lock objects
  Private lock lock = new Reentrantlock ();

@Override
public void Run () {
while (true) {
try {
Locking
      Lock.lock ();
if (Tickets > 0) {
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "being sold" + (tickets--) + "Ticket");
}
} finally {
Release lock
  Lock.unlock ();
}
}
}

}

Thread pool: (line constructor Each thread code ends and does not die, but returns to the thread pool again to become idle, waiting for the next object to be used)

The cost of starting a new thread is high because it involves interacting with the operating system, and using the thread pool can improve performance.

JDK5 New Executors factory class to generate thread pool

Method:

public static Exectorservice Newcachedthreadpool (): Turn on the thread pool with caching capability

public static Exectorservice newfixedthreadpool (int nthreads): Creates a specified number of thread pools

public static Exectorservice Newsinglethreadexector (): Create a

The return value of these methods is the Exectorsservice object, which represents a thread pool that can execute runnable objects and the threads represented by callable objects

public static void Main (string[] args) {
creates a thread pool object that controls how many thread objects to create.
Public static Executorservice newfixedthreadpool (int nthreads)
  Executorservice pool = Executors.newfixedthreadpool (2);

can execute Runnable object or thread represented by callable object

Future<?> Submit (Runnable Task): Submits a Runnable task for execution and returns a future that represents the task.
<T> future<t> Submit (callable<t> Task): A task that submits a return value is used to execute, returning a pending result of the task to the future.


  Pool.submit (new myrunnable ());
Pool.submit (New myrunnable ());

End thread Pool
  Pool.shutdown (); //If you do not add a closing sentence, the thread returns to the pool for other people to use
}

public class Myrunnable implements Runnable {

@Override
public void Run () {
for (int x = 0; x < + × x + +) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + x);
}
}

}

Timer:

Timer: (extends Object) a tool that a thread uses to schedule tasks to perform later in a background thread. You can schedule a task to execute once, or repeat it periodically.

  Timer()
Creates a new timer.

  schedule(TimerTask task, long delay)
Schedules the specified task to execute after a specified delay.

  schedule(TimerTask task, long delay, long period)
Schedule a specified task to start repeating fixed deferred execution from a specified delay

  cancel()
Terminates this timer, discarding all currently scheduled tasks.

TimerTask (extends Object implements Runnable)

  TimerTask()
Create a new Timer task

  run()
The action to be performed by this timer task.

  cancel()
Cancels this timer task.

Is the startup of the JVM virtual machine single-threaded or multithreaded?
Multi-threaded.
The reason is that garbage collection threads also have to start first, otherwise memory overflow can occur easily.
Now the garbage collection thread plus the previous main thread, the minimum boot two threads, so the JVM startup is actually multi-threaded.

2. Design mode

1) Single case design mode

A Hungry man type:

Lazy Type: (Lazy loading)

Javase Review Summary 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.