Java game programming (1) threads

Source: Internet
Author: User

1. in Java, you only need to generate a thread and start it. ImplementationCodeAs follows:

Thread mythread = new thread ();

Mythread. Start ();

After a thread is generated, the thread's run () method is called. But in fact, it does not do anything. If you want the run () method to do something, there are three basic methods.

(1) extended Thread class

The first method for a job specified by a thread is to extend the Thread class and overwrite the run () method.

Example: public class mythread extends thread {

Public void run (){

{System. Out. println ("do something cool here ");

}

}

Mythread thread = new mythread ();

Thread. Start ();

(2) Implement the runnable interface

The extension Thread class is very simple, but does not write a new class to start the thread. It must also run a thread to implement the class extension. The following describes how to implement the runnable () interface to specify a task for a thread. The implementation code is as follows:

Public class myclass extends someotherclass implements runnable {

Public myclass (){

Thread thread = new thread (this );

Thread. Start ();

}

Public void run (){

System. Out. println ("do something cool here ");

}

}

In the code, the constructor of myclass starts a new thread, and the constructor of the thread class references a runnable object as a parameter.

The runnable object is the task that starts the thread to execute.

(3) Use anonymous internal classes

If a new class cannot be generated or the runnable interface cannot be implemented, you can use an anonymous internal class to specify a task for the thread. The implementation code is as follows:

New thread (){

Public void run (){

System. Out. println ("do something cool here ");

}

}. Start ();

2. Wait for the thread to finish

If you want the current thread to wait for another thread, you can use the join () method to implement the following:

Mythread. Join ();

When a player exits the game, the join () method ensures that all the threads in the game are run before cleaning.

Thread sleep: thread. Sleep (1000 );

3. Thread Synchronization

Use the keyword synchronized to implement synchronization. Only one method can be run at a time.

Example:

Public class maze {

Private int playerx;

Private int playery;

Public synchronized Boolean isatexit (){

Return (playerx = 0 & playery = 0 );

}

Public synchronized void setpositon (int x, int y ){

Playerx = X;

Playery = y;

}

}

In addition to synchronizing methods, you can also synchronize objects. For example, the above Code can be as follows:

Public synchronized class maze {

Private int playerx;

Private int playery;

Public void Boolean isatexit (){

Isatexit (this ){

Return (playerx = 0 & playery = 0 );

}

}

Public void setposition (int x, int y ){

Setposition (this ){

Playerx = X;

Playery = y;

}

}

4. Use wait () and Policy ()

Assume that two threads need to exchange information and set thread a to wait for thread B to send a message. The implementation code is as follows:

// Thread

Public void waitformessage (){

While (hasmessage = false ){

Thread. Sleep (100 );

}

}

// Thread B

Public void setmessage (string message ){

.......

Hasmessage = true;

}

Although the solution is feasible, it is very benzene because thread a checks whether thread B sends messages every 100 milliseconds. If thread a falls asleep, the message may be too late. What about other threads and other messages?

A better way is to keep thread a idle and notify thread a when thread B sends a message. The wait () and notify () methods provide this function.

The following is the code that thread a waits for thread B to send a message;

// Thread

Public synchronized void waitformessage (){

Try {Wait ();

}

Catch (interruptedexception ex ){}

}

// Thread B

Public synchronized void setmessage (string message ){

......

Notify ();

}

It can be seen that thread B calls the notify () method and leaves the synchronization method (release this lock ). Thread a acquires the lock and completes the synchronization code quickly.

If the thread has not received the notification all the time, it is equal to letting the thread rest for a specified time, but it cannot be determined whether the thread returns timeout or has received the notification. Another method, notify (), notifies all threads waiting for the same lock.

Java thread: All graphics applicationsProgramThere are at least two threads that run the code, the main thread and the AWT event-derived thread.

The main thread is the "Main" thread of the program. He starts execution using the main () method of the main class of the program. The AWT event-derived thread processes user input events, such as mouse clicks, key-clicks, and Window Scaling. The following are some cases where threads are required: install a large number of files from the local file system

For any network communication, such as sending high scores to the server, or generating terrain for any massive computing.

Related Article

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.